活跃农民
- 积分
- 419
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-7-28
- 最后登录
- 1970-1-1
|
发现一个bug。 不止j,i也可能出现在previous pair里面。添加了一个test case,更新了代码。- /*
- The idea is: use hashmaps to cache all the visited pair sum. We maintain two hashmaps: sum2index2cnt is to cache the sum and index frequency in pairs to make the sum; sum2paircnt is to store how many pairs can make that sum. NOTE here, i,j could appear in the previous visited pairs to make -sum, which is not valid. So we need to make sure there is a previous pair of -sum that does not contain i,j index.
-
- Two loops O(N^2) time, O(N^2) space
- */
- bool fourSumTwoLoops(vector<int>& nums) {
- int n = nums.size();
- if(n < 4) return false;
- unordered_map<int, unordered_map<int, int>> sum2index2cnt; // key is the sum of a pair, value is a map as well: key is index in the pair, value is the cnt of this index in all valid pairs to make such sum
- unordered_map<int, int> sum2paircnt;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < i; j++) {
- int sum = nums[i] + nums[j];
- if(sum2index2cnt.count(-sum)) { // if there are pairs previous visited that can make -sum.
- int cnt_i_pair = sum2index2cnt[-sum].count(i) ? sum2index2cnt[-sum][i] : 0;
- int cnt_j_pair = sum2index2cnt[-sum].count(j) ? sum2index2cnt[-sum][j] : 0;
- if(cnt_i_pair + cnt_j_pair != sum2paircnt[-sum]) return true; // if there is previous pair that neither contains i or j.
- }
- sum2index2cnt[sum][i]++;
- sum2index2cnt[sum][j]++;
- sum2paircnt[sum]++;
- }
- }
- return false;
- }
- int main(int argc, const char * argv[]) {
- // insert code here...
- vector<int> nums = {1,2,3,4,5,6,7,8,9,10};
- cout << fourSumTwoLoops(nums) << endl;
-
- nums = vector<int>({-1,-1,-1,3});
- cout << fourSumTwoLoops(nums) << endl;
-
- nums = vector<int>({-10,4,1,3});
- cout << fourSumTwoLoops(nums) << endl;
- return 0;
- }
复制代码 |
|