136. Single Number
Problem:
Analysis:
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?
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Use XOR, because any number XOR itself is 0. We can set result's initial value to 0, 0 XOR any number is that number.
Solution:
class Solution { public int singleNumber(int[] nums) { int res = 0; for (int n: nums) { res ^= n; } return res; } }
评论
发表评论