Feb22/23--Grind75

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值