博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
136. Single Number
阅读量:4655 次
发布时间:2019-06-09

本文共 1231 字,大约阅读时间需要 4 分钟。

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?

 

Solution 1:

思路: 用set检验是不是有重复的。把没有重复的加到set里面,有重复的从set里面remove掉 .最后set里面只存在一个数,用iterator给读出来即可。

注意corner case: 数组只有一个数的时候就直接读出。

 

Time Complexity: O(N)

public int singleNumber(int[] nums) {        if(nums.length==1)        {            return nums[0];        }        int number=0;        Set
res=new HashSet
(); for(int i=0;i

Solution 2:

没有想出来不用extra space的,参考了discussion

https://discuss.leetcode.com/topic/47560/xor-java-solution/5

要熟悉XOR的工作原理

Reference:

 

X     Y     Output

0     0     0

0     1     1

1     0     1

1     1     0 

Tricks: 0^a=a 2,a^b=b^a 3,a^a=0, a^1=a(inversion)

 

题目思路:because the xor has three properties. 1,0^a=a 2,a^b=b^a 3,a^a=0

so swapping the number would not change the output at the end, we can see the list as all the same numbers are adjacent. the same numbers would be 0 after xor. the one remaining would be the answer.

 

因为除了一个数之外其他的数都有一个相同的数,所以最后剩下来的就是 0^a=a极其巧妙.

public int singleNumber(int[] nums) {        int count=0;        for(int i=0;i

 

转载于:https://www.cnblogs.com/Machelsky/p/5856283.html

你可能感兴趣的文章
[转] 树状数组学习
查看>>
ASP.NET-ActionFilter过滤器用法实例
查看>>
将url的查询参数解析成字典对象
查看>>
Redis与RabbitMQ作为消息队列的比较
查看>>
mybatis实战教程三:mybatis和springmvc整合
查看>>
Java多线程:Semaphore
查看>>
960栅格化优势
查看>>
LSP原则—关于正方形不是长方形
查看>>
Android内核开发 相关工具及源码下载汇总
查看>>
多线程(二)--NSThread基本使用
查看>>
git command
查看>>
使用Photon引擎进行unity网络游戏开发(二)——Photon常用类介绍
查看>>
html里 调整字间距
查看>>
RabbitMQ的Vhost,Exchange,Queue原理分析
查看>>
Mac上编写C语言程序
查看>>
251.Flatten 2D Vector
查看>>
WLS Exception: Need to specify class name in environment or system property Solution
查看>>
人见人爱A^B
查看>>
消除头文件
查看>>
Android中数据文件解析(Json解析)
查看>>