LeetCode 15 -- 3Sum
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).
1 public class ThreeSum { 2 public List<List<Integer>> threeSum(int[] nums){ 3 Arrays.sort(nums); 4 List<List<Integer>> lists = new ArrayList<List<Integer>>(); 5 List<Integer> list = new ArrayList<Integer>(); 6 for(int i = 0 ; i < nums.length ; i++){ 7 int leftPoint = i + 1; 8 int rightPoint = nums.length - 1; 9 while( leftPoint < rightPoint){ 10 if (nums[i] + nums[leftPoint] + nums[rightPoint] == 0){ 11 list.add(nums[i]); 12 list.add(nums[leftPoint]); 13 list.add(nums[rightPoint]); 14 lists.add((ArrayList<Integer>) list); 15 } 16 17 18 else if(nums[i] + nums[leftPoint] + nums[rightPoint] > 0 ) 19 rightPoint--; 20 else 21 leftPoint++; 22 } 23 } 24 return lists; 25 } 26 }
貌似没有考虑好边界问题,需要修改。超时了。
http://www.programcreek.com/2012/12/leetcode-3sum/
1 public class ThreeSum { 2 public List<List<Integer>> threeSum(int[] nums) { 3 List<List<Integer>> result = new ArrayList<List<Integer>>(); 4 5 if (nums.length < 3) 6 return result; 7 8 // sort array 9 Arrays.sort(nums); 10 11 for (int i = 0; i < nums.length - 2; i++) { 12 // //avoid duplicate solutions 13 if (i == 0 || nums[i] > nums[i - 1]) { 14 15 int negate = -nums[i]; 16 17 int start = i + 1; 18 int end = nums.length - 1; 19 20 while (start < end) { 21 // case 1 22 if (nums[start] + nums[end] == negate) { 23 ArrayList<Integer> temp = new ArrayList<Integer>(); 24 temp.add(nums[i]); 25 temp.add(nums[start]); 26 temp.add(nums[end]); 27 28 result.add(temp); 29 start++; 30 end--; 31 // avoid duplicate solutions 32 while (start < end && nums[end] == nums[end + 1]) 33 end--; 34 35 while (start < end && nums[start] == nums[start - 1]) 36 start++; 37 // case 2 38 } else if (nums[start] + nums[end] < negate) { 39 start++; 40 // case 3 41 } else { 42 end--; 43 } 44 } 45 46 } 47 } 48 49 return result; 50 } 51 }
http://stackoverflow.com/questions/10732522/difference-between-two-similar-algorithms-of-3sum
通过hashSet实现
posted on 2015-07-29 15:28 myshuangwaiwai 阅读(137) 评论(0) 编辑 收藏 举报