leetcode18 4sum

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

题目:

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


思路:

和3sum的思路差不多。这里只贴代码。


代码:

 public List<List<Integer>> fourSum(int[] nums, int target) {
	        List<List<Integer>> list= new ArrayList<List<Integer>>();
	        if(nums==null || nums.length<4)
	        	return list;
	        
	        quickSort(nums,0,nums.length-1);
	        int length=nums.length;
	        int first=0;
	        int two=1;
	        int three=2;
	        int four=3;
	        while(first<length-3){
	        	two=first+1;
	        	while(two<length-2){
	        		three=two+1;
	        		four=length-1;
	        		while(three<four){
	        			if(nums[three]+nums[four]>target-nums[first]-nums[two])
	        				four--;
	        			if(nums[three]+nums[four]<target-nums[first]-nums[two])
	        				three++;
	        			if(nums[three]+nums[four]==target-nums[first]-nums[two] && three<four){
	        				List<Integer> listThree=new ArrayList<Integer>();
	        				listThree.add(nums[first]);
	        				listThree.add(nums[two]);
	        				listThree.add(nums[three]);
	        				listThree.add(nums[four]);
	        				list.add(listThree);
	        				three++;
	        				while(three<four){
	        					if(nums[three]==nums[three-1])
		        					three++;
	        					if(nums[three]!=nums[three-1])
	        						break;
	        				}
	        				
	        			}
	        				
	        		}
	        		two++;
	    			while( two<length-2 && nums[two-1]==nums[two] )
	    				two++;
	        	}
	        	first++;
				while( first<length-3 && nums[first-1]==nums[first] )
					first++;
	        	
	        }
	        return list;
	    }
	 
	 public static 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值