当前位置: 代码迷 >> 综合 >> LintCode-三数之和
  详细解决方案

LintCode-三数之和

热度:90   发布时间:2023-10-13 08:41:39.0

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

class Solution {
    
public:/*** @param numbers: Give an array numbers of n integer* @return: Find all unique triplets in the array which gives the sum of zero.*/vector<vector<int>> threeSum(vector<int> &numbers) {
    // write your code herevector<vector<int>> result;int i=0,j=0,k=0;int size = numbers.size();if (size < 3){
    return result;}sort(numbers.begin(), numbers.end());for(k = 0; k < size - 2 ;k++ ){
    if(k > 0 && numbers[k]==numbers[k-1]) {
    continue;}for(i = k+1,j = size-1;i<j;){
    if(i > k+1 && numbers[i]==numbers[i-1]) {
    i++;continue;}if(j<size-1 && numbers[j]==numbers[j+1]) {
    j--;continue;}int sum = numbers[i] + numbers[j] + numbers[k];if(sum == 0) {
    vector<int> temp;temp.push_back(numbers[k]);temp.push_back(numbers[i]);temp.push_back(numbers[j]);result.push_back(temp);i++;j--;}else if(sum >0) {
    j--;}else {
    i++;}}}return result;}
};