136. Single Number
- Total Accepted: 158682
- Total Submissions: 306217
- Difficulty: Easy
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?
给你一个数组,数组中只有一个数出现的次数不是两次,输出这个数。要求O(n)复杂度并且不开额外空间
简单的异或应用,x ^ x = 0,遍历一遍就行了
public class Solution {
public int singleNumber(int[] nums) {
int len = nums.length;
int temp = nums[0];
for(int i=1;i<len;i++){
temp ^= nums[i];
}
return temp;
}
}