Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2:
Input: [3,3,7,7,10,11,11] Output: 10
Note: Your solution should run in O(log n) time and O(1) space.
想法如下
- 利用 XOR 的特性來解這題。因為每個數都會出現兩次,所以 XOR 過後,都會歸零,最後剩下的就是答案
Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int singleNonDuplicate(int[] nums) { | |
int ans = 0; | |
for(int n : nums) { | |
ans ^= n; | |
} | |
return ans; | |
} | |
} |
沒有留言:
張貼留言