虽然题目是从Hash Table tag里搜出来的,但用HashMap/HashSet只是解法之一,有些题目的奇技淫巧还需看其他解法,我尽量整理在一起。
/**
* hash map中存遍历的数组元素和它的index,遍历的过程中比较有没有符合条件的值,碰到则返回
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(hm.get(target-nums[i])!=null){
return new int[]{i,hm.get(target-nums[i])};
}
hm.put(nums[i],i);
}
return new int[]{1,1,1};
}
}
/**
* 用hash map的常规思路O(n) 9 ms 39.3 MB
*/
class Solution1 {
public int singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int num : nums){
map.put(num,map.getOrDefault(num,0)+1);
}
for(int num : nums){
if(map.get(num)==1){
return num;
}
}
return -1;
}
}
/**
* 数学解法2∗(a+b+c)−(a+a+b+b+c)=c 复杂度6 ms,39.1 MB
*/
class Solution2 {
public int singleNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
int setSum=0, numSum=0;
for(int num:nums){
if(!set.contains(num)){
set.add(num);
setSum+=num;
}
numSum+=num;
}
return 2*setSum-numSum;
}
}
Bit Manipulation
a | b | a ^ b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
a⊕0=a
a⊕a=0
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
/**
* 神奇解法 1 ms 38.9 MB
*/
class Solution3 {
public int singleNumber(int[] nums) {
int a=0;
for (int num : nums){
a^=num;
}
return a;
}
}
Example 1:
Input: n = 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
/**
* 举例得知非快乐数最后会进入重复循环,所以用set记录有过的sum of the squares of its digits。如果有重复sum出现说明不是快乐数,如果结果为1,判断是快乐数
* 1 ms 36.4 MB
*/
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(true){
int sum = squareSum(n);
if(sum==1){
return true;
}
if(set.contains(sum)){
return false;
}else{
set.add(sum);
}
n=sum;
}
}
private int squareSum(int n){
int sum = 0;
while(n>0){
int d=n % 10;
sum += d*d;
n /= 10;
}
return sum;
}
}
/**
* 快慢指针的神奇算法,当不快乐数字进入死循环后,两指针总要碰面
* 0 ms 35.7 MB
*/
class Solution {
public boolean isHappy(int n) {
if(n==1||n==-1){return true;}
int slow=n, fast=n;
while(true){
slow=squareSum(slow);
fast=squareSum(fast);
fast=squareSum(fast);
if(fast==1){return true;}
else if(fast==slow){return false;}
}
}
private int squareSum(int n){
int sum = 0;
while(n>0){
int d=n % 10;
sum += d*d;
n /= 10;
}
return sum;
}