Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 136. Single Number #2

Open
Woodyiiiiiii opened this issue Apr 15, 2020 · 0 comments
Open

LeetCode 136. Single Number #2

Woodyiiiiiii opened this issue Apr 15, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Apr 15, 2020

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

题目意思是一个非空数组中,有一个数出现一次,其他数都出现两次,找出这个只出现一次的数。要求空间复杂度O(1),时间复杂度O(n)。

一开始我是用哈希表的特点,遍历数组元素,如果哈希表中没有出现这个数,那么存进哈希表(key为元素,value是元素下标)。最后哈希表肯定剩下唯一的键值对,返回key就可以了。注意remove(), keySet()方法的使用和遍历哈希表。

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer, Integer> myMap = new HashMap<>();
        int i = 0;
        
        for (int num : nums) {
            if (myMap.containsKey(num)) myMap.remove(num);
            else myMap.put(num, i);
            ++i;
        }
        
        for (Integer key : myMap.keySet()) {
            return key;
        }
        return 0;
    }
}

显然这个方法的空间复杂度不是常数级。
对于数,还有位运算的想法,异或的作用是相同的数异或为0,不同的不为0。利用位异或的特点:

  • x ^ x = 0
  • 0 ^ x = x

可以得到x ^ y ^ x = y的公式。遍历异或数组即可。

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int v : nums) {
            result ^= v;
        }
        
        return result;
    }
}
func singleNumber(nums []int) int {
	var res int
	for _, v := range nums {
		res ^= v
	}
	return res
}

扩展:如果一次数出现一次,其他数出现偶数次,都可以用异或方法找出。

参考:
LeetCode原题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant