Leetcode水題——3Sum
阿新 • • 發佈:2018-12-12
題目
題解
這題還是比較簡單的,首先進行排序(對於沒有按下標輸出要求的題目,向考慮排序),排好序後,找第一個數,設第一個數下標為i,則第二個數從i+1開始找,因為i之前的數字的所有組合都已經找出來了,計算第一個數與第二數的和,取反,根據二分法查詢,查詢範圍為第二個數的下標到陣列結尾,另外當第一個數為正數時就可以退出了,因為正數後面都為正數,不可能為0,另外題目要求不能重複,一些邊界條件還是要注意
程式碼
class Solution { public: int binary(vector<int>&a,int first,int end,int number) { int mid; while (first <= end) { mid = (first + end) / 2; if (a[mid] == number) return mid; if (a[mid] < number) first = mid + 1; else end = mid-1; } return -1; } vector<vector<int>> threeSum(vector<int>& a) { sort(a.begin(), a.end()); vector<vector<int>> result0; int i,j,n=a.size(); for (i = 0;i < n;i++) { if (a[i] > 0) break; if (i == 0 || a[i] != a[i - 1]) { for (j = i + 1;j < n;j++) { int temp = 0 - a[i] - a[j]; int result = binary(a, j + 1, n - 1, temp); if ((j==i+1||a[j]!=a[j-1])&&result != -1) { vector<int> temp; temp.push_back(a[i]); temp.push_back(a[j]); temp.push_back(a[result]); result0.push_back(temp); } } } } return result0; } };