Leetcode之SingleNumber I/II/III

Single Number I

题解

https://leetcode.com/problems/single-number/

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


相同的数异或为0。
0和任何数异或都为这个数。
所以 全部的数异或就为那一个数。


Code

public class Solution {
    public int singleNumber(int[] nums) {
          int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res = res ^ nums[i];
        }
        return res;
    }
}

Single Number II

题解

https://leetcode.com/problems/single-number-ii/

Single Number II
  Given an array of integers, every element appears three times except for one. Find that single one.

求得遍历每一个数,求得某一位上,1的个数,如果存在3的余数,则那个数就是多出来的Single one 速度很慢。

Code

public class Solution {
    public int singleNumber(int[] nums) {
        int length = nums.length;
        int res = 0;
        for (int i = 0; i < 32; i++) {
            int mask = 1 << i;
            int count = 0;
            for (int j = 0; j < length; j++) {
                if ((nums[j] & mask) == mask) {
                    count++;
                }
            }
            if (count % 3 != 0) {
                res += mask;
            }
        }
        return res;
    }
}

Single Number III

题解

https://leetcode.com/problems/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].

此题的解法,对于三个题目都适用,只是方法实在是太笨了,无奈,网上的妙趣的解法我没有通透。目前就先写这个方法吧,等哪天我弄明白了,再贴出代码。

Code

public class Solution{
    public int[] singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        int[] res = new int[2];
        int i = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                res[i] = entry.getKey();
                i++;
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值