136. 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?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

1 class Solution {
2     public int singleNumber(int[] nums) {
3         int ans = 0;
4         for (int i = 0; i < nums.length; ++i) {
5             ans = ans ^ nums[i];
6         }
7         return ans;
8     }
9 }

 

posted @ 2020-02-17 22:49  hyx1  阅读(67)  评论(0编辑  收藏  举报