求大神给下c++版的完整解法,包括头文件,主函数,类体。请在文中注明一下具体而详细的思路方法,我学了哈希表和二叉树,一直都不太懂,感觉怪怪的。想要看看大神完整连贯的思路,模仿一下。c++解法,求大神自己敲一下,不要复制粘贴,菜鸡伤不起。
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
vector> fourSum(vector& nums, int target) { int n = nums.size(); QuickSort(nums,0,n-1); int i,j,k,s,sum,t1,t2; vector<int> turple; vector<vector<int>> result; if(n < 4) return result; t1 = nums[0]; for(i=0;i<n-3;i++) { if(i && t1 == nums[i]) continue; t2 = nums[i+1]; for(j=i+1;j<n-2;j++) { if(t2 == nums[j] && j >i+1) continue; sum = target - nums[i] - nums[j]; k = j+1; s = n-1; while(k<s) { if(nums[k] + nums[s] == sum) { turple.push_back(nums[i]); turple.push_back(nums[j]); turple.push_back(nums[k]); turple.push_back(nums[s]); result.push_back(turple); turple.clear(); k++; s--; } else if(nums[k] + nums[s] < sum) k++; else s--; } t2 = nums[j]; } t1 = nums[i]; } result.erase(unique(result.begin(),result.end()),result.end()); return result; } void QuickSort(vector<int>&nums,int low,int high) { if(low<high) { int pivot = nums[low]; int first = low; int last = high; while(first<last) { while(nums[last] > pivot && last > first) { --last; } nums[first] = nums[last]; while(nums[first] <= pivot && last >first) { ++first; } nums[last] = nums[first]; } nums[first] = pivot; QuickSort(nums,low,first-1); QuickSort(nums,first+1,high); } else return; }
- 1 回答
- 0 关注
- 792 浏览
添加回答
举报
0/150
提交
取消