首页 > 其他 > 详细

136. Single Number

时间:2018-10-08 13:45:58      阅读:225      评论:0      收藏:0      [点我收藏+]

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 /*Time: O(n), Space: O(1)
 2 exclusive or operation:
 3 1 XOR 1 = 0
 4 1 XOR 0 = 1
 5 0 XOR 1 = 1
 6 0 XOR 0 = 0
 7 0 XOR A = A  关键:0异或任何数还是任何数
 8 */
 9 public int singleNumber(int[] nums) {
10         if (nums == null || nums.length == 0) {
11             return 0;
12         }
13         
14         int result = 0;
15         
16         for (int i = 0; i < nums.length; i++) {
17             result = result ^ nums[i];
18         }
19         
20         return result;
21     }

 

136. Single Number

原文:https://www.cnblogs.com/jessie2009/p/9753809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!