您的位置:首页 > 其它

3sum

2018-02-12 11:08 253 查看
given an array s of integers n , 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.
code example :
   /// <summary>
        /// given an array s of n integers ,are there element 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:Element in triplets (a,b,c) must be in non-descending order 
        /// the solusion set must not contain duplicate triplets .
        /// </summary>
        /// <param name="nums"></param>
        /// <returns></returns>
        static List<List<int>> threeSum(int[] nums)
        {
            List<List<int>> result = new List<List<int>>();
            if (nums.Length < 3) return result;
            Array.Sort(nums);
            int target = 0;
            for(int i = 0; i < nums.Length - 2; ++i)
            {
                if (i > 0 && nums[i] == nums[i - 1]) continue;
                int j = i + 1;
                int k = nums.Length - 1;
                while (j < k)
                {
                    if (nums[i] + nums[j] + nums[k] < target)
                    {
                        ++j;
                        while (nums[j] == nums[j - 1] && j < k) ++j;

                    }else if (nums[i] + nums[j] + nums[k] > target)
                    {
                        --k;
                        while (nums[k] == nums[k + 1] && j < k) --k;

                    }
                    else
                    {
                        result.Add(new List<int>() { nums[i], nums[j], nums[k] });
                        ++j;
                        --k;
                        while (nums[j] == nums[j - 1] && j < k) ++j;
                        while (nums[k] == nums[k + 1] && j < k) --k;
                    }
                }
            }
            return result;
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algrithm