1数组中的重复数字
Leetcode 287. Find the DuplicateNumber 寻找重复数字
Given an array nums containing n +1 integers where each integer is between 1 and n (inclusive),prove that at least one duplicate number must exist. Assume that there is onlyone duplicate number, find the duplicate one.
Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than O(n2).
- There is only one duplicate number in the array, but it could be repeated more than once.
利用鸽巢原理(n个鸽子放到n-1个笼子中一定有一个笼子里面有两个鸽子),使用二分查找找到重复的数字,1~n范围的数,首先找到中位数mid,然后遍历数组看看数组中有多少个小于等于mid的数count,如果count > mid说明重复数在1~mid中,否则在mid+1~n中。
Leetcode 442. Find All Duplicatesin an Array 找出数组中的所有重复数字(剑指offer 51)
Given an array of integers, 1 ≤ a[i]≤ n (n = size of array), some elementsappear twice and others appear once.
Find all the elements that appear twice inthis array.
Could you do it without extra space and inO(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
遍历数组,出现了什么数就改变以这个数当做index的位置的值(是负数就已经存在了,是正数就设成负数)
2. 数组中的单个数字
136. Single Number 只有一个数字出现一次,其余出现两次
Given an array of integers, every elementappears twice exceptfor one. Find that single one.
一个数字与自己做异或操作会是0,所以只需把数组中所有的数进行异或操作,则可以找出只出现一次的数字
260. Single Number III 两个数字出现一次,其余出现两次的
Given an array of numbers nums
, inwhich exactly two elements appear only once and all the other elements appearexactly twice.
Find the two elements that appear only once.
For example:
Given nums= [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
与上题的做法类似,先将数组中所有的数字做异或操作,最后得到的值是要求得的两个数字a,b异或之后的结果,考虑到异或的性质,某个位为1就代表一定有a或者b的这个位是1,则通过异或得到的结果中为1的一位来对数组进行分组,然后再对分组之后得到的结果分别进行异或操作就能得到想要的a,b了。
Leetcode 137. Single Number II 只有一个出现一次,其余出现3次
Given an array of integers,every element appears three timesexcept for one, which appears exactly once. Find that single one.
对于出现三次的情况就是使用下面的公式
once = (once^ nums[i]) & ~twice;
twice = (twice ^ nums[i]) & ~once
数字出现一次的时候once是数字本身,twice是0,出现两次once是0,twice是数字本身,出现三次的时候once和twice都是0 ,从而可以得到那个只出现一次的数字
扩展:出现多次可以用这种该方法去扩展
3. 构建乘积数组
Leetcode 238. Product of Array Except Self 构建乘积数组(剑指offer 52)
Given an array of n integerswhere n > 1, nums, return an array output such that output[i] isequal to the product of all the elements ofnums except nums[i].
Solve it without division andin O(n).
For example, given [1,2,3,4], return [24,12,8,6].
使用两个数组存储新生成的数组的左右两边(以i来分隔)