leetcode15 3sum

来源:互联网 发布:sem与seo的区别 编辑:程序博客网 时间:2024/06/05 20:09

我的leetcode代码已放入github:https://github.com/gaohongbin/leetcode

题目:

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

翻译:

找到三个数相加之和为0,并且三个数是非递减顺序排列的。

思路:

对于2sum的问题,我们先对数组进行排列,然后用两个指针low和high分别指向数组的第一个数和最后一个数,因为是排过序的,所以当nums[low]+nums[high]之和小于target时,就low++,如果之和大于target,就high--,如果之和等于target,就将相应的nums[low],nums[high]保存起来。


对于3Sum问题,无非是外面加一层嵌套,相应的变换target为target-nums[one].


里面有个快排,纯属自己练手,可以引用线程的快排函数。


代码:

  public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> list=new ArrayList<List<Integer>>();if(nums==null || nums.length<3)return list;quickSort(nums,0,nums.length-1);int length=nums.length;int first=0;int two=first+1;int three=length-1;while(first<length-2){two=first+1;three=length-1;while(two<three){if(nums[two]+nums[three]>0-(nums[first]) && two<three){three--;}if(nums[two]+nums[three]<0-nums[first] && two<three){two++;}if(nums[two]+nums[three]==0-nums[first] && two<three){List<Integer> listSum=new ArrayList<Integer>();listSum.add(nums[first]);listSum.add(nums[two]);listSum.add(nums[three]);list.add(listSum);two++;while(two<three){if(nums[two-1]==nums[two])two++;    if(nums[two-1]!=nums[two])break;}  }}first++;while( first<length-2 && nums[first-1]==nums[first] )first++;}return list;    }public void quickSort(int[] nums,int low,int high){if(low>=high || nums==null)return ;int length=nums.length;int mid=nums[low];int i=low,j=high;while(i<j){while(nums[j]>mid && j>i)j--;nums[i]=nums[j];while(nums[i]<=mid && i<j)i++;nums[j]=nums[i];}nums[j]=mid;quickSort(nums,low,j-1);quickSort(nums,j+1,high);}


0 0
原创粉丝点击