首页 > 其他 > 详细

260. Single Number III

时间:2017-08-03 22:39:34      阅读:176      评论:0      收藏:0      [点我收藏+]

260. 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].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

 

上两个的升级版,但是跟上两个思路又完全不同。真是。。。

两种做法,一个位运算肯定是技巧性很高的,一个是set维护。

Java set做法:

  遍历这个数组,第一次出现的添加进去,只要出现了第二次,则remove,剩下的就是单个了的数集合了,也适用用于找出数组中成对出现数中的所有单个数。最后把这个set集合元素添到数组就行了。

  查了资料,貌似不能直接把一个set集合转换成Array,toArray也只能装换成object,参考可见:https://ask.helplib.com/106360

public class Solution {
    public int[] singleNumber(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        for(int n : nums) {
            if(!set.contains(n)) {
                set.add(n);
            }else {
                set.remove(n);
            }
        }
        
        int[] ans = new int[set.size()];
        int cnt = 0;
        
        for(int n:set) {
            ans[cnt++] = n;
        }
        return ans;
    }
}

 

位运算做法:

 

 

260. Single Number III

原文:http://www.cnblogs.com/zhangmingzhao/p/7282441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!