题解 | #三数之和#

三数之和

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;
        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;
    }
}

两重遍历没什么好说的,为了升序,先将数组排序,这样放入结果时就是升序的了。
核心在于去重复,这里引入了2个变量preI,preJ就是为了记录上一次num[i]和num[j]的值,例如 -2 0 0 2 2,当 {-2 0,2}第一次被加入后 j++, num[j]依然为0,这时候就要跳过去。
顺带一提的是: a+b+c=0中,由于a<=b<=c,而数列升序,所以c的下标一定要大于 i,j,否则,不能保证升序顺序
全部评论

相关推荐

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