leetcode经典题目及解法记录
来源:互联网 发布:dom编程艺术第二版txt 编辑:程序博客网 时间:2024/06/04 22:09
Question15 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法如下:
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList(); Arrays.sort(nums); for(int i = 0; i < nums.length; i++){ if(i==0||(i>0&&nums[i]!=nums[i-1])){ int lo=i+1, hi=nums.length-1, sum=0-nums[i]; while(lo<hi){ if(nums[lo]+nums[hi]==sum){ res.add(Arrays.asList(nums[i], nums[lo], nums[hi])); while(lo<hi&&nums[lo]==nums[lo+1]) lo++; while(lo<hi&&nums[hi]==nums[hi-1]) hi--; lo++; hi--; }else if(nums[lo]+nums[hi]<sum) lo++; else hi--; } } } return res;}
Question16 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解法如下:
public int threeSumClosest(int[] nums, int target) { int res = nums[0]+nums[1]+nums[nums.length-1]; Arrays.sort(nums); for(int i = 0; i < nums.length-2; i++){ int lo = i+1, hi = nums.length-1; while(lo < hi){ int sum = nums[i]+nums[lo]+nums[hi]; if(sum==target) return sum; if(sum<target) lo++; else hi--; if(Math.abs(res-target)>Math.abs(sum-target)) res = sum; } } return res;}
- leetcode经典题目及解法记录
- leetcode经典解法
- Radar题目及解法
- ZigZag Conversion题目及解法
- Leetcode 经典题目题解
- leetcode题目记录
- 【leetcode】Keyboard Row题目的C++解法
- 喷水装置(一)题目及解法
- 喷水装置(二)题目及解法
- 会场安排问题题目及解法
- LeetCode经典题目备忘I
- leetcode 题目记录:7,8
- 【LeetCode】 242.Valid Anagram 解法及注释
- 【LeetCode】44. Wildcard Matching解法及注释
- 【LeetCode】48. Rotate Image解法及注释
- 【LeetCode】49. Group Anagrams解法及注释
- 【LeetCode】61. Rotate List解法及分析
- 【LeetCode】62. Unique Paths解法及注释
- 用jsp返回json
- Java基础概念
- 对象存储系统概念
- 洛谷P2023 [AHOI2009]维护序列
- 一分钟修改网页中的内容
- leetcode经典题目及解法记录
- matlab cell
- skynet 学习笔记
- 5、上卷下拉效果--动画篇
- LL(1)文法
- github----向开源框架提交pr的过程
- Codeforces Round #441 (Div. 1, by Moscow Team Olympiad) F. Royal Questions
- angular4中动画及路由动画的使用
- 【UVA11374】Airport Express