题解 | #数组中只出现一次的两个数字#

数组中只出现一次的两个数字

http://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8

using System;
using System.Collections.Generic;
using System.Linq;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param array int整型一维数组 
     * @return int整型一维数组
     */
    public List<int> FindNumsAppearOnce (List<int> array) {
        // write code here
        List<int> ans=new List<int>(){0,0};
        int temp=0;
        array.ForEach(x=>temp^=x);
        int mask=1;
        while((temp&mask)==0)
            mask<<=1;
        foreach(var x in array)
        {
            if((x&mask)==0)
                ans[0]^=x;
            else
                ans[1]^=x;
        }
        if(ans[0]>ans[1])
        {
            int temp2=ans[1];
            ans[1]=ans[0];
            ans[0]=temp2;
        }
        return ans;
    }
}关键在在于根据异或结果将数组分成两队。如果题目是三个只出现一次的数,那就没有办法了。
全部评论

相关推荐

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