设为首页 加入收藏

TOP

LeetCode -- Single Number III
2015-11-21 00:54:19 来源: 作者: 【 】 浏览:1
Tags:LeetCode Single Number III
题目描述:


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
  
   ();
    	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
   
    (); foreach(var k in hash.Keys){ if(hash[k] == 1){ ret.Add(k); } if(ret.Count == 2){ break; } } return ret.ToArray(); } }
   
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LeetCode -- H-Index II 下一篇LeetCode 29 Divide Two Integers..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: