18. 4Sum
2016-12-10 23:51
274 查看
二刷。
还是部分遍历+滑窗。
难点在于如何跳过重复的元素。
滑窗过程中遇到重复元素,和前2个固定坐标遇到重复元素是不一样的。
So u shall handle them in different ways respectively.
滑窗过程中,一旦判定成功,左右坐标的下一个如果相同,都没有判断的必要,所以要往二者之间不停地滑。“小心地滑”(beware of the slippery floor) 标识牌翻译成 slide cautiously
固定坐标遇到和上一个相等也要滑。。
二刷。
固定2个,然后夹逼。
注意去重,然后别忘了一开始排序。。。
Time: O(nlgn)排序 + O(n³)
Space: O(n)
还是部分遍历+滑窗。
难点在于如何跳过重复的元素。
滑窗过程中遇到重复元素,和前2个固定坐标遇到重复元素是不一样的。
So u shall handle them in different ways respectively.
滑窗过程中,一旦判定成功,左右坐标的下一个如果相同,都没有判断的必要,所以要往二者之间不停地滑。“小心地滑”(beware of the slippery floor) 标识牌翻译成 slide cautiously
固定坐标遇到和上一个相等也要滑。。
public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(nums.length < 4) return res; Arrays.sort(nums); for(int i = 0; i < nums.length-3;i++) { for(int j = i+1; j < nums.length-2;j++) { int L = j+1; int R = nums.length-1; int total = nums[i] + nums[j]; while(L < R) { if(total + nums[L] + nums[R] > target) R--; else if(total + nums[L] + nums[R] < target) L++; else { List<Integer> tempList = new ArrayList<>(); tempList.add(nums[i]);tempList.add(nums[j]);tempList.add(nums[L]);tempList.add(nums[R]); res.add(new ArrayList<>(tempList)); while(L < R && nums[L] == nums[L+1]) L++; while(L < R && nums[R] == nums[R-1]) R--; R--;L++; } } while(j < nums.length-2 && nums[j] == nums[j+1]) j++; } while(i < nums.length -1 && nums[i] == nums[i+1]) i++; } return res; } }
二刷。
固定2个,然后夹逼。
注意去重,然后别忘了一开始排序。。。
Time: O(nlgn)排序 + O(n³)
Space: O(n)
public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<>(); if (nums.length < 4) return res; Arrays.sort(nums); for (int i = 0; i < nums.length - 3; i++) { for (int j = i + 1; j < nums.length - 2; j++) { int left = target - nums[i] - nums[j]; int l = j + 1; int r = nums.length - 1; while (l < r) { if (nums[l] + nums[r] < left) { l ++; } else if (nums[l] + nums[r] > left) { r --; } else { List<Integer> tempList = new ArrayList<>(); tempList.add(nums[i]); tempList.add(nums[j]); tempList.add(nums[l ++]); tempList.add(nums[r --]); res.add(tempList); while (l < r && nums[l] == nums[l-1]) { l ++; } while (l < r && nums[r] == nums[r+1]) { r --; } } } while (j < nums.length - 1 && nums[j] == nums[j+1]) { j ++; } } while (i < nums.length - 1 && nums[i] == nums[i+1]) { i ++; } } return res; } }
相关文章推荐
- IE10以下的img标签问题
- 创建单链表并赋值,要求遍历能输出1~9
- this关节字
- ListView详解
- eclipse中使用maven创建Java web项目的详细步骤
- freeline集成到Android Studio
- Oracle升级前备份和失败回退
- robotframework中的pybot和robot的区别
- C++编程基础(1)
- Python语言编程(一)
- C/C++编译器、编辑器、IDE
- 视频会议及流媒体十大开源项目
- Android开发 百度地图开发(定位、传感器应用)
- 笔记:oracle关于使用代理主键还是逻辑主键的好?
- 历届试题 核桃的数量
- 那些年陪伴我的老师+我期待的师生关系
- FastDFS使用经验分享
- 转载两篇关于WSGI的文章
- 为什么循环里的gets()和fgets()在前面有一个scanf时,会跳过第一个的输出
- Java被忽略的基本知识(三)