今天下午到了图书馆先刷了三道leetcode的题目,虽然是medium难度,可是这三道题目主要考察的还是位运算符的熟练程度还有一些基本的计算机操作的思想。
136.
leetcode[136] Single Number
给定一个数组,里面有一个数只出现一次,其他的出现两次,找出出现一次的数。
这道题本身是可以用hash map来做,因为他是一道牵扯到是不是重复的问题, 但是因为对那部分内容还不熟悉,所以先是考虑是不是可以用bit manipulation。
class Solution { public: int singleNumber(int A[], int n) { int sum = 0; for (int i = 0; i < n; i++) { sum ^= A[i]; } return sum; } };非常简单的一道题,主要是要想到异或这个操作可以消除全部相同的数所以最后的sum就是唯一的一个。
leetcode[137] Single Number II
题目和上题类似,这里给的数组仅有一个数出现一次,其他的出现3次。返回那个出现一次的数。
这题还是比较难想到的。不想上一题只要异或一下就可以了,不用额外操作。
int singleNumber(int A[], int n) { int ans = 0; for (int i = 0; i < 32; i++) { int cnt = 0, bit = 1 << i; for (int j = 0; j < n; j++) { if (A[j] & bit) cnt++; } if (cnt % 3 != 0) ans |= bit; } return ans; }主要是要想到每一位的具体情况,如果这一位的一的个数可以被三整除说明那个唯一的数这一位是0.
260. Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
这时候的思路就是要把这两个分到两组里面,然后分别找到两组里面的单独的这个。
public
class
Solution {
public
int
[] singleNumber(
int
[] nums) {
int
[] res =
new
int
[
2
];
int
temp =
0
;
for
(
int
n : nums) temp ^= n;
temp &= -temp;
// Get the last set bit
for
(
int
n : nums){
if
((n & temp) ==
0
) res[
0
] ^= n;
else
res[
1
] ^= n;
}
return
res;
}
}
|