136. Single Number

2018/04/12 leetcode 共 542 字,约 2 分钟

Title

the problem link

Given an 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?

题目大意:除了一个数字都出现了两次,找出这个只出现一次的数字

Solution

自己写的ac,用的哈希表,其实可以用异或,还有数学方法,因此自己与自己异或是0,哈哈哈哈

//cpp:
class Solution {
public:
	int singleNumber(vector<int>& nums) {
		unordered_map<int, int> umap;
		for (int i = 0; i < nums.size(); i++) {
			umap[nums[i]]++;
		}
		for (auto it : umap) {
			if (it.second == 1) {
				return it.first;
			}
		}
		return -1;
	}
};

2∗(a+b+c)−(a+a+b+b+c)=c

Search

    Table of Contents