LeetCode -- Single Number III

来源:互联网 发布:sql server denty_rank 编辑:程序博客网 时间:2024/05/16 01:29
题目描述:


Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.


For example:


Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].


在一个数组中,只有两个数只出现了1次,其余数都出现了两次。


思路:
如果空间允许,还是建议直接使用哈希表。


实现代码:


public class Solution {    public int[] SingleNumber(int[] nums)     {        var hash = new Dictionary<int,int>();    for(var i = 0;i < nums.Length; i++)    {    if(hash.ContainsKey(nums[i])){    hash[nums[i]] ++;    }    else{    hash.Add(nums[i], 1);    }    }        var ret = new List<int>();    foreach(var k in hash.Keys){    if(hash[k] == 1){    ret.Add(k);    }    if(ret.Count == 2){        break;    }    }        return ret.ToArray();    }}


1 0
原创粉丝点击