【LeetCode OJ 015】3Sum

題目鏈接:https://leetcode.com/problems/3sum/

題目: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.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)

題意:給定一個數組,找出所有和爲0的三個數,添加到ArrayList<Interger>中。要求這三個數按非降序排列,並且ArrayList不能重複。

示例代碼:

public class Solution 
{
	  public List<List<Integer>> threeSum(int[] nums) 
		 {
		        List<List<Integer>> result=new ArrayList<List<Integer>>();
		        int length=nums.length;
		        if(nums==null||length<3)
		        	return result;
		        //對目標數組按照升序排序
		        Arrays.sort(nums);
		        for(int i=0;i<length-2;i++)
		        {
		        	//略過相同的數
		        	if(i!=0&&nums[i]==nums[i-1])
		        	{
		        		continue;
		        	}
		        	int left=i+1;
		 	        int right=length-1;
		 	        //在nums[i]的右側尋找兩個數,值得它們爲0
		        	while(left<right)
			        {
			        	int a1=nums[left];
			        	int a2=nums[right];
			        	int sum=a1+a2+nums[i];
			        	if (sum==0)
						{
			        			ArrayList<Integer> list=new ArrayList<Integer>();
			        			list.add(nums[i]);
			        			list.add(a1);
			        			list.add(a2);
			        			result.add(list);
			        			
			        			left++;
								right--;
								while (left < right && nums[left] == nums[left - 1]) 
								{ 
									//左側略過相同的結果
									left++;
								}
								while (left < right && nums[right] == nums[right + 1]) 
								{
									//右側略過相同的結果
									right--;
								}
						}
			        		else if(sum>0) //sum>0,說明右側的數大了,應該往左邊移動
			        		{
			        			right--;
			        		} 
			        		else  //反之要往右邊移動
			        		{
			        			left++;
			        		}
			        	
			        }
		        }
		        return result;
		 }
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章