3 Single Number

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?

/*
Example1:
Input: [2,2,1]
Output: 1
*/

public class Solution{
	public int singleNumber(int[] numbers){
		int x = 0;
		for(int a : nums){
			x ^= a;
		}
		return x;
	}
}

^異或運算
根據二進制運算計算得到結果
比如2是0010,1是0001
那麼抑或就是0011,十進制就是3

這邊0異或2還是2,2異或2得0,也就是說成對出現同樣的數異或之後結果爲0
那麼出現不同的數,就會是最終的結果

時間複雜度是線性的:O(n)
空間複雜度是:O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章