zoukankan      html  css  js  c++  java
  • 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]
    ]

    Solution:

    此题的关键在于如何避免duplicate triplets. 此处解决方法为只考虑首次出现的值,以[-4,-1,-1,-1,0,1,2]为例,循环第一次到-1时,所有跟-1有关的triplets [-1,0,1],[-1,-1,2]已经出现,则第二次循环到-1的时候,忽略这个subloop一直到发现下一个非-1的值,
    此处为0.
    public class Solution {
        public IList<IList<int>> ThreeSum(int[] nums) {
            List<int> newList = nums.ToList();
                List<IList<int>> returnList = new List<IList<int>>();
                newList.Sort();
                for(int i = 0; i < newList.Count() -2; i++)
                {
                    if((i == 0)||( (newList[i] != newList[i - 1])))
                    {
                        int low = i + 1;
                        int high = nums.Length - 1;
                        int sum = 0 - newList[i];
                        while(low < high)
                        {
                            if(newList[low]+newList[high] == sum)
                            {
                                returnList.Add(new List<int>() { newList[i?], newList[low], newList[high] });
                                while ((low < high) && (newList[low] == newList[low + 1])) low++;//duplicate
                                while ((low < high) && (newList[high] == newList[high - 1])) high--;//duplicate
                                low++;
                                high--;
                            }
                            else if(newList[low]+newList[high] < sum)
                            {
                                low++;
                            }
                            else
                            {
                                high--;
                            }
                        }
                    }
                }
                return returnList;
            
        }
    }
  • 相关阅读:
    RPM的使用详细演示安装,删除和查询
    GCC 参数详解
    简述configure、pkgconfig、pkg_config_path三者的关系
    RPM查询篇
    Linux软件安装之RPM的安装技巧
    linux gcc 编译时头文件和库文件搜索路径
    嵌入式开发.C语言面试题
    GCC几个选项学习
    asp.net mvc 自定权限实现
    使用Jquery EasyUi常见问题解决方案
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5782509.html
Copyright © 2011-2022 走看看