码迷,mamicode.com
首页 > 其他好文 > 详细

136. Single Number

时间:2018-10-08 13:59:22      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:without   null   ever   length   com   should   find   opera   linear   

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

标签:without   null   ever   length   com   should   find   opera   linear   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!