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

[LeetCode]single-number

时间:2018-08-16 14:05:03      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:++   color   app   ber   参与   总结   .so   https   tail   

题目: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?

题目理解:一个数组中有一个数是单独的,其他的数都是成对出现的。

简单做法:

  首先,对数组进行排序,然后遍历数组,成对比较数组元素,找出首个不相等的数组元素,返回该元素,则该元素就是数组中唯一的单个元素。由于排序使用的是快排,故满足需求。

代码:

 1 import java.util.Arrays;
 2 public class Solution {
 3     public int singleNumber(int[] A) {
 4         if(A.length == 1) return A[0];
 5         Arrays.sort(A);
 6         for(int i = 1;i < A.length;){
 7             if(A[i-1] != A[i]){
 8                 return A[i-1];
 9             }
10             i += 2;
11         }
12         return 0;
13     }
14 }

进阶版做法(使用位运算):

  异或运算中二个参与运算的对象(二进制)相应位相同,值为0,否则为1.即1^1=0,1^0=1,0^0=0,0^1=1。由这个特性,得到从零开始异或数组元素中每个值,最终剩下的就是数组中单独的那个数,成对的数都异或为0了。

例如:数组为 1 2 1 4 4

0^1 = 0000 0001 = 1

1^2 = 0000 0011 = 3

3^1 = 0000 0010 = 2

2^4 = 0000 0110 = 6

6^4 = 0000 0010 = 2

最后得到数组中唯一的数2.

代码:

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

参考资料:

位运算总结:https://blog.csdn.net/sinat_35121480/article/details/53510793

 

[LeetCode]single-number

标签:++   color   app   ber   参与   总结   .so   https   tail   

原文地址:https://www.cnblogs.com/whl-shtudy/p/9486158.html

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