• 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;
            
        }
    }
  • 相关阅读:
    svg 画地图
    小议 localStorage
    .NET Core 的缓存篇之MemoryCache
    .NET Core Session的简单使用
    .NET Core 使用NLog日志记录
    .NET Core 技巧汇总篇
    .NET Core 获取自定义配置文件信息
    微信支付教程系列之公众号支付
    微信支付教程系列之扫码支付
    微信支付教程系列之现金红包
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5782509.html
Copyright © 2020-2023  润新知