Leetcode#15. 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: 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]
]
題意解析:
    這道題通過我們仔細分析題意來看,其實是尋找兩個數的和等於一個特定的值,如果直接開三層循環遍歷的話,會使算法複雜度變高,一個可以採用的建議是先將這個數組排好序,按順序進行選擇。
    首先選取一個數nums[i],令start = i + 1, end = length - 1,。然後判斷三個數的和,若和大於0,則令end--,和小於0,則令start++,找到結果後,將其放入輸出結果即可。
    這裏還要注意一點,就是去重問題,這裏當有重複的時候,自動將i自增即可。
    一種c++的實現如下:
#include<iostream>
#include<vector>
#include<cstdlib>
#include<cstdio>
using namespace std;

class Solution {
public:
       vector<vector<int> > threeSum(vector<int>& nums) {
    	vector<vector<int> > result;
        sort(nums); 
        int n = nums.size();
        for(int i = 0; i < n; i++) {
        	int temp = nums[i];
        	int start = 1+i;
        	int end = n-1;
        	while(start < end) {
        		if(nums[start]+nums[end] == 0-temp) {
        			vector<int> one_solution;
        			one_solution.push_back(temp);
        			one_solution.push_back(nums[start]);
					one_solution.push_back(nums[end]);
					sort(one_solution);
                    result.push_back(one_solution);
					while (start < end && nums[start] == one_solution[1]) start++;
					while (start < end && nums[end] == one_solution[2]) end--;
				} else if (nums[start] + nums[end] > 0 - temp){
					end--;
				} else {
					start++;
				}
			}
            while (i + 1 < nums.size() && nums[i + 1] == nums[i]) 
            i++;
		}
		return result;
    }
    
    void sort(vector<int>& nums) {
    	int n = nums.size();
    	for(int i = 0; i < n-1; i++)
    		for(int j = 0; j < n-i-1; j++) {
    			int temp;
    			if(nums[j] > nums[j+1]) {
					swap(nums[j], nums[j+1]);
				}
		}
	}
	void swap(int &a, int &b) {
		int temp;
		temp = a;
		a = b;
		b = temp;
	}
};


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