zoukankan      html  css  js  c++  java
  • leetcode: 3Sum

    http://oj.leetcode.com/problems/3sum/

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
    
    Note:
    Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    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)
     

    思路

    1. 先排序,然后对于a[i],找到后面所有令a[i] + a[j] + a[k] = 0的组合。
    2. 注意所有的三元组不能有重复,这就需要在循环里做一些处理把重复的数字跳过。
     1 class Solution {
     2 public:
     3     vector<vector<int> > threeSum(vector<int> &num) {
     4         vector<vector<int> > result;
     5         int size = num.size(), tmp;
     6         
     7         sort(num.begin(), num.end());
     8         
     9         for (int i = 0; i < size; ) {
    10             int j = i + 1, k = size - 1;
    11             
    12             while (j < k) {
    13                 int sum = num[i] + num[j] + num[k];
    14                 
    15                 if (0 == sum) {
    16                     vector<int> v;
    17                     v.push_back(num[i]);
    18                     v.push_back(num[j]);
    19                     v.push_back(num[k]);
    20                     result.push_back(v);
    21                 }
    22                 
    23                 if (sum > 0) {
    24                     tmp = k - 1;
    25                     while ((j < tmp) && (num[tmp] == num[k])) {
    26                         --tmp;
    27                     }
    28                     k = tmp;
    29                 }
    30                 else {
    31                     tmp = j + 1;
    32                     while ((tmp < k) && (num[j] == num[tmp])) {
    33                         ++tmp;
    34                     }
    35                     j = tmp;
    36                 }
    37             }
    38             
    39             tmp = i + 1;
    40             
    41             while ((tmp < size) && (num[tmp] == num[i])) {
    42                 ++tmp;
    43             }
    44             i = tmp;
    45         }
    46         
    47         return result;
    48     }
    49 };
  • 相关阅读:
    日志
    JAVA字符串类
    JAVA包
    JAVA面向对象
    JAVA数组
    JAVA循环结构
    JAVA程序调试
    JAVA条件判断
    JAVA算术运算符
    JAVA数据类型
  • 原文地址:https://www.cnblogs.com/panda_lin/p/3sum.html
Copyright © 2011-2022 走看看