【leetcode】 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.

分析:http://leetcode.com/2010/04/finding-all-unique-triplets-that-sums.html

如果不用set来去除重复元素的话,需要在指针扫描的过程中进行判重。

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       	vector<vector<int> >  res;
   		sort(num.begin(), num.end());
   		for(int i=0; i<num.size(); i++){
			//cout<<"here"<<endl;
			if(i>0 && num[i]==num[i-1])
				continue;
			int ptr1=i+1; 
			int ptr2=num.size()-1;
			while(ptr1 < ptr2){
				if(num[i]+num[ptr1]+num[ptr2] < 0)
					ptr1++;
				else if(num[i]+num[ptr1]+num[ptr2] > 0)
					ptr2--;
				else{
					vector<int> v;
					v.push_back(num[i]);
					v.push_back(num[ptr1]);
					v.push_back(num[ptr2]);
					res.push_back(v);
					ptr1++; ptr2--;
					while(ptr1<num.size() && num[ptr1]==num[ptr1-1])
						ptr1++;
					while(ptr2>=0 && num[ptr2]==num[ptr2+1])
						ptr2--;
				}
			}// end while loop
		}//end for loop
		return res;
    }
};

再来一个Java版本的

import java.util.ArrayList;
import java.util.Arrays;


public class Solution {


    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {		
        // Start typing your Java solution below
        // DO NOT write main() function
		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();		
		Arrays.sort(num);
		
		for(int i=0; i<num.length; i++){
			int ptr1=i+1, ptr2=num.length-1;
			if(i>0 && num[i]==num[i-1])
				continue;
//			search from two sides
			while(ptr1 < ptr2){
//				smaller than 0
				if(num[i]+num[ptr1]+num[ptr2] < 0)
					ptr1++;
//				larger than 0
				else if(num[i]+num[ptr1]+num[ptr2] > 0)
					ptr2--;
//				equal to zero
				else{
					ArrayList<Integer> element = new ArrayList<Integer>();
					element.add(new Integer(num[i]));
					element.add(new Integer(num[ptr1]));
					element.add(new Integer(num[ptr2]));
//					update results
					result.add(element);
					ptr1++; ptr2--;
					while(ptr1<num.length && num[ptr1]==num[ptr1-1])
						ptr1++;
					while(ptr2>i && num[ptr2]==num[ptr2+1])
						ptr2--;
				}
			}// end while loop
		}// end for loop
		return result;       
        
    }// end method
	
}// end class


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值