1. two sum--1
要看清题目
2.Best Time to Buy and Sell Stock--121
如何用一个loop解决问题??
3. Majority Element--169
先用了HashMap,time complexity是O(n). space complexity是O(n).
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int ans = 10000000;
for(int i: nums){
map.put(i, map.getOrDefault(i, 0)+1);
}
for(int i:map.keySet()){
if(map.get(i) > nums.length/2){
ans = i;
}
}
return ans;
}
}
看看有没有更省空间的做法
Boyer-Moore Voting Algorithm -> space complexity O(log n), Time complexity O(n)
主要思路是,因为A majority element occurs in more than half the indices in an array.
This is the insight: the majority element won’t change after removing those two unequal elements. Why? Because by crossing out the two elements, you either decreased one instance of the majority element, or zero. Not two — because the elements are unequal.
具体证明:
Why Moore's Voting Algorithm works – Rohan Prinja –
代码
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int initial = nums[0];
for(int i: nums){
if(count == 0){
initial = i;
}
if(i == initial){
count++;
}else{
count--;
}
}
return initial;
}
}