标签:elements solution contain target example
Total Accepted: 35045 Total Submissions: 162380My Submissions
Question Solution
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)
分析:如果依次遍历时间复杂度是n^4,现在是n^3,采用的策略是控制两个变量,然后从两头向中间一遍扫描行数据
public class Solution {
void Sort(int[] dz, int s, int e){
if(s==e-1)
{
if(dz[s]>dz[e])
{
int mid=dz[s];
dz[s]=dz[e];
dz[e]=mid;
}
}
else if(s<e)
{
int cur=s;
int j=e;
while(cur!=j)
{
if(cur<j)
{
if(dz[cur]>dz[j])
{
int mid=dz[cur];
dz[cur]=dz[j];
dz[j]=mid;
mid=cur;
cur=j;
j=mid;
}
else
j--;
}
else
{
if(dz[cur]<dz[j])
{
int mid=dz[cur];
dz[cur]=dz[j];
dz[j]=mid;
mid=cur;
cur=j;
j=mid;
}
else
j++;
}
}
Sort(dz, s, cur-1);
Sort(dz, cur+1, e);
}
}
public List<List<Integer>> fourSum(int[] nums, int target) {
Map<String, Integer> z=new HashMap<String, Integer>();
List<List<Integer>> x=new ArrayList<List<Integer>>();
List<Integer> y=new ArrayList<Integer>();
if(nums.length<4)
return x;
Sort(nums, 0, nums.length-1);
int min=Math.abs(nums[0]+nums[1]+nums[2]+nums[3]-target);
boolean open=false;
if(min==0)
{
open=true;
y=new ArrayList<Integer>();
y.add(nums[0]);
y.add(nums[1]);
y.add(nums[2]);
y.add(nums[3]);
x.add(y);
z.put(Integer.toString(nums[0])+" "+Integer.toString(nums[1])+" "+Integer.toString(nums[2])+" "+Integer.toString(nums[3]),1);
}
for(int i=0;i<nums.length-3;i++)
{
for(int m=i+1;m<nums.length-2;m++)
{
int j=m+1;
int k=nums.length-1;
while(j<k)
{
if(nums[i]+nums[m]+nums[j]+nums[k]>target)
{
k--;
}
else if(nums[i]+nums[m]+nums[j]+nums[k]<target)
{
j++;
}
else
{
if(!open)
{
if(z.get(Integer.toString(nums[i])+" "+Integer.toString(nums[m])+" "+Integer.toString(nums[j])+" "+Integer.toString(nums[k]))==null)
{
y=new ArrayList<Integer>();
y.add(nums[i]);
y.add(nums[m]);
y.add(nums[j]);
y.add(nums[k]);
x.add(y);
z.put(Integer.toString(nums[i])+" "+Integer.toString(nums[m])+" "+Integer.toString(nums[j])+" "+Integer.toString(nums[k]),1);
}
}
else
open=false;
j++;
}
}
}
}
return x;
}
}
标签:elements solution contain target example
原文地址:http://7061299.blog.51cto.com/7051299/1654980