这是剑指offer数组中重复的数字那个题,直接使用的swap函数
class Solution { public: // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false bool duplicate(int numbers[], int length, int* duplication) { if(length <= 0){ *duplication = -1; return false; } int start = 0; while(start < length){ if(numbers[start] == numbers[numbers[start]] && numbers[start] != start){ *duplication = numbers[start]; return true; } if(start == numbers[start]){ start++; continue; } int index = numbers[start]; while(numbers[start] != numbers[index]){ swap(numbers[start],numbers[index]); index = numbers[start]; } } *duplication = -1; return false; } };
字符串的全排列也用到了swap
class Solution { public: vector<string> Permutation(string str) { if(str.size() == 0) return ans; length = str.size(); int begin = 0; Permutation(str,begin); //res.clear(); set<string>::iterator it; for (it = res.begin(); it != res.end(); ++it) ans.push_back(*it); return ans; } void Permutation(string str,int begin){ if(begin == length){ res.insert(str); return; } for(int i = begin;i < length;i++){ swap(str[begin],str[i]); Permutation(str,begin+1); swap(str[begin],str[i]); } } set<string> res; vector<string> ans; int length = 0; };