首页 > 其他 > 详细

Single Number i,ii,iii

时间:2016-12-01 14:07:53      阅读:161      评论:0      收藏:0      [点我收藏+]

136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Bit: a ^ a = 0;

public class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
        for(int n : nums){
            res ^= n;
        }
        return res;
    }
}

 

137. Single Number II

public class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0 ; i < nums.length ; i++){
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            if(entry.getValue() == 1)
                return entry.getKey();
        }
        return 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].

public class Solution {
    public int[] singleNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int n: nums){
            if(!set.add(n)){
                set.remove(n);
            }
        }
        Iterator<Integer> it = set.iterator();
        int[] res = new int[2];
        int start = 0;
        while(it.hasNext() && start < res.length){
            res[start] = it.next();
            start++;
        }
        return res;
    }
}

 

二刷可以研究bit做法

Single Number i,ii,iii

原文:http://www.cnblogs.com/joannacode/p/6121399.html

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