题解 | #三数之和#

三数之和

http://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param num int整型一维数组 
     * @return int整型二维数组
     */
    public List<List<int>> threeSum (List<int> num) {
        // write code here 
        List<List<int>> ans=new List<List<int>>();
        num.Sort();
        int preI=-101;
        int preJ=-101;
        int preK=-101;
        for(int i=0;i<num.Count-2;i++)
        {
            if(num[i]==preI)
                continue;
            else
                preI=num[i];
            int j=i+1;                
            int k=num.Count-1;
            while(j<k)
            {
                var sum=num[i]+num[j]+num[k];
                if(sum==0)
                {
                    if(preJ==num[j] && preK==num[k])
                    {
                        j++;
                        k--;
                        continue;
                    }
                    ans.Add(new List<int>{num[i],num[j],num[k]});
                    preK=num[k];
                    preJ=num[j];
                    j++;
                    k--;
                }
                else if(sum>0)
                {
                    preK=num[k];
                    k--;
                }
                else
                {
                    preJ=num[j];
                    j++;
                }
                
            }
        }
//         int preI=-101;
//         int preJ=-101;
//         for(int i=0;i<num.Count;i++)
//         {
//             if(num[i]==preI)
//                 continue;
//             else
//                 preI=num[i];
//             for(int j=i+1;j<num.Count;j++)
//             {
//                 if(preJ==num[j])
//                     continue;
//                 else
//                     preJ=num[j];
                
//                 var s=-1*(num[i]+num[j]);
//                 if(num.Contains(s))
//                 {
//                     if(num.LastIndexOf(s)>j)
//                     {
//                         ans.Add(new List<int>{num[i],num[j],s});
// //                         if(s==0 && num[j]==0)
// //                         {
// //                             i=num.LastIndexOf(s);
// //                             break;
// //                         }
                            
//                     }
//                 }
                    
//             }
//         }
        return ans;
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务