Tuesday, August 23, 2016

Leetcode 15. 3Sum

 public class Solution {  
   public IList<IList<int>> ThreeSum(int[] nums) {  
     List<IList<int>> ret = new List<IList<int>>();  
     if (nums == null || nums.Length < 3)  
     {  
       return ret;  
     }  
     Array.Sort(nums);  
     int a = 0;  
     HashSet<string> hash = new HashSet<string>();  
     while (a <= nums.Length - 3)  
     {  
       if (a > 0 && nums[a] == nums[a-1])  
       {  
         a++;  
         continue;  
       }  
       int b = a + 1;  
       int c = nums.Length - 1;  
       while (b < c)  
       {  
         int sum = nums[a] + nums[b] + nums[c];  
         string array = String.Join(",", new int[3]{nums[a], nums[b], nums[c]});  
         if (sum == 0 && !hash.Contains(array))  
         {  
           List<int> res = new List<int>();  
           res.Add(nums[a]);  
           res.Add(nums[b]);  
           res.Add(nums[c]);  
           hash.Add(array);  
           ret.Add(res);  
           b++;  
           c--;  
         }  
         else if (sum < 0)  
         {  
           b++;  
         }  
         else  
         {  
           c--;  
         }  
       }  
       a++;  
     }  
     return ret;  
   }  
 }  

No comments:

Post a Comment