算法刷题记录(LeetCode 691-720)

692. Top K Frequent Words

    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer> occurrence=new HashMap<>();
        for (String word:words){
            occurrence.put(word,occurrence.getOrDefault(word,0)+1);
        }
        var wordSet=occurrence.keySet();
        final int[] counter = {0};
        List<String> ans=new ArrayList<>();
        wordSet.stream().sorted((o1,o2)->{
            if (occurrence.get(o1).equals(occurrence.get(o2))){
                return o1.compareTo(o2);
            }
            return occurrence.get(o2)-occurrence.get(o1);
        }).forEach(o->{
            if (counter[0] <k){
                ans.add(o);
                counter[0]++;
            }
        });
        return ans;
    }

693. Binary Number with Alternating Bits

class Solution {
public:
    bool hasAlternatingBits(int n) {
        if (n < 3) {
            return true;
        }
        int i = 31;
        while ((n & (1 << i)) == 0) {
            i--;
        }
        int target = 1;
        while (i >= 0) {
            if (target > 0) {
                if ((n & (1 << i)) == 0) {
                    return false;
                }
            } else {
                if ((n & (1 << i)) > 0) {
                    return false;
                }
            }
            target = 1 - target;
            i--;
        }
        return true;

    }
};

697. Degree of an Array

class Solution {
    public static class ValInfo{
        int cnt=1;
        int start=-1;
        int end=-1;

        public ValInfo(int cnt, int start, int end) {
            this.cnt = cnt;
            this.start = start;
            this.end = end;
        }
    }
    public int findShortestSubArray(int[] nums) {
        int maxCnt=1;
        HashSet<Integer> cnt=new HashSet<>();
        HashMap<Integer,ValInfo> dict=new HashMap<>();
        dict.put(nums[0],new ValInfo(1,0,0));
        cnt.add(nums[0]);
        for (int i = 1; i < nums.length; i++) {
            ValInfo obj;
            if (!dict.containsKey(nums[i])){
                obj=new ValInfo(1,i,i);
                dict.put(nums[i],obj);
            }
            else{
                obj=dict.get(nums[i]);
                obj.cnt++;
                obj.end=i;
            }
            if (obj.cnt>maxCnt){
                maxCnt=obj.cnt;
                cnt.clear();
            }
            if (obj.cnt==maxCnt){
                cnt.add(nums[i]);
            }
        }
        int min_ans=Integer.MAX_VALUE;
        for (int val:cnt){
            min_ans=Math.min(min_ans,dict.get(val).end-dict.get(val).start+1);
        }
        return min_ans;
    }
}

700. Search in a Binary Search Tree

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        if (root== nullptr){
            return nullptr;
        }
        if (root->val==val){
            return root;
        }
        if (root->val>val){
            return searchBST(root->left,val);
        }
        return searchBST(root->right,val);
    }
};

701. Insert into a Binary Search Tree

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root==null){
            return new TreeNode(val);
        }
        bfs(root,val);
        return root;
    }
    public void bfs(TreeNode root,int val){
        if (root.val>val){
            if (root.left==null){
                root.left= new TreeNode(val);
            }
            else{
                bfs(root.left,val);
            }
        }
        else{
            if (root.right==null){
                root.right= new TreeNode(val);
            }
            else{
                bfs(root.right,val);
            }
        }
    }
}

703. Kth Largest Element in a Stream

class KthLargest {
    int currValue=Integer.MIN_VALUE;
    int size;
    PriorityQueue<Integer> queue;
    public KthLargest(int k, int[] nums) {
        Arrays.sort(nums);
        size=k-1;
        queue=new PriorityQueue<>();
        for (int i=0;i<k-1;i++){
            queue.add(nums[nums.length-1-i]);
        }
        if (k<=nums.length){
            currValue=nums[nums.length-k];
        }
    }

    public int add(int val) {
        if (currValue>val){
            return currValue;
        }
        queue.offer(val);
        currValue=queue.poll();
        return currValue;
    }
}

705. Design HashSet

class MyHashSet {
    boolean[] value=new boolean[1001000];
    public MyHashSet() {
        
    }

    public void add(int key) {
        value[key]=true;
    }

    public void remove(int key) {
        value[key]=false;
    }

    public boolean contains(int key) {
        return value[key];
    }
}

706. Design HashMap

class MyHashMap {
public:
    int val[1001000]={0};
    bool used[1001000]={false};
    MyHashMap() {

    }

    void put(int key, int value) {
        val[key]=value;
        used[key]= true;
    }

    int get(int key) {
        if (!used[key]){
            return -1;
        }
        return val[key];
    }

    void remove(int key) {
        used[key]= false;
    }
};

707. Design Linked List

class LinkedList{
public:
    int val;
    LinkedList* next= nullptr;
    explicit LinkedList(int val) : val(val) {}
};
class MyLinkedList {
    int size=0;
    LinkedList* head=new LinkedList(-1);
public:
    MyLinkedList() {

    }
    int get(int index) {
        if (index>=size){
            return -1;
        }
        return getPrev(index+1)->val;
    }

    void addAtHead(int val) {
        auto* newHead=new LinkedList(-1);
        head->val=val;
        newHead->next=head;
        head=newHead;
        size++;
    }

    void addAtTail(int val) {
        auto* newTail=new LinkedList(val);
        auto* tail=getTail();
        tail->next=newTail;
        size++;
    }
    LinkedList* getTail(){
        auto* curr=head;
        while (curr->next!= nullptr){
            curr=curr->next;
        }
        return curr;
    }
    void addAtIndex(int index, int val) {
        if (index>size){
            return;
        }
        if (index==0){
            addAtHead(val);
            return;
        }
        if (index==size){
            addAtTail(val);
            return;
        }
        auto* prev= getPrev(index);
        auto* next=prev->next;
        auto* node=new LinkedList(val);
        node->next=next;
        prev->next=node;
        size++;
    }
    LinkedList * getPrev(int idx){
        auto* curr=head->next;
        idx--;
        int curr_idx=0;
        while (curr_idx<idx){
            curr=curr->next;
            curr_idx++;
        }
        return curr;
    }

    void deleteAtIndex(int index) {
        if(index>=size){
            return;
        }
        if (index==0){
            auto* first=head->next;
            head->next=first->next;
            delete first;
            size--;
            return;
        }
        auto* prev= getPrev(index);
        auto* waitingDelete = prev->next;
        prev->next=waitingDelete->next;
        delete waitingDelete;
        size--;

    }
};

709. To Lower Case

class Solution {
    public String toLowerCase(String s) {
        return s.toLowerCase();
    }
}

*710. Random Pick with Blacklist

class Solution {

    //将(0,n-m)映射到(0,n)
    HashSet<Integer> smaller=new HashSet<>();
    HashSet<Integer> larger=new HashSet<>();
    HashMap<Integer,Integer>mapper=new HashMap<>();
    Random random=new Random();
    int size=0;
    int blackSize=0;
    int top;
    int curr_idx;
    public Solution(int n, int[] blacklist) {
        size=n;
        blackSize=blacklist.length;
        top=size-blackSize;
        curr_idx=top;
        for (int val:blacklist) {
            if(val>=top){
                larger.add(val);
            }
            else{
                smaller.add(val);
            }
        }
    }

    public int pick() {
        int randVal=random.nextInt(top);
        if (randVal<top&&!smaller.contains(randVal)){
            return randVal;
        }
        if (smaller.contains(randVal)){
            if (mapper.containsKey(randVal)){
                return mapper.get(randVal);
            }
            while (larger.contains(curr_idx)){
                curr_idx++;
            }
            mapper.put(randVal,curr_idx);
            curr_idx++;
            return mapper.get(randVal);
        }
        return randVal;
    }

}


713. Subarray Product Less Than K

双指针

class Solution {
public:
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        int ans=0;
        // std::sort(nums.begin(), nums.end());
        int left=0;
        int right=left;
        int curr_product=1;
        while (right<nums.size()){
            curr_product*=nums[right];
            right++;
            while (curr_product>=k){
                if (left>=right){
                    return ans;
                }
                curr_product/=nums[left];
                left++;
            }
            ans+=(right-left);
        }
        return ans;
    }
};

*714. Best Time to Buy and Sell Stock with Transaction Fee

    int maxProfit(vector<int>& prices, int fee) {
        vector<vector<int>> cache(prices.size()+1,vector<int>(2,0));
        cache[0][0]=-prices[0];
        cache[0][1]=0;
        for (int i = 1; i <= prices.size(); ++i) {
            cache[i][0]=max(cache[i-1][0],cache[i-1][1]-prices[i-1]);
            cache[i][1]=max(cache[i-1][1],cache[i-1][0]+prices[i-1]-fee);
        }
        return cache[prices.size()][1];
    }

717. 1-bit and 2-bit Characters

    bool isOneBitCharacter(vector<int>& bits) {
        int curr=0;
        while (curr<bits.size()-1){
            if (bits[curr]==1){
                curr+=2;
            }
            else{
                curr++;
            }
        }
        return curr==bits.size()-1;
    }

720. Longest Word in Dictionary

Trie 注意排序

class PrefixTree {
    static class PrefixTreeNode {
        boolean end = false;
        HashMap<Character, PrefixTreeNode> children = new HashMap<>();
    }

    PrefixTreeNode tree = new PrefixTreeNode();

    public boolean insert(String word) {
        PrefixTreeNode curr = tree;
        int continuous_failure=0;
        PrefixTreeNode node=null;
        for (int i = 0; i < word.length(); i++) {
            if (!curr.children.containsKey(word.charAt(i))) {
                if (continuous_failure==1){
                    node.children.remove(word.charAt(i-1));
                    return false;
                }
                node=curr;
                continuous_failure++;

                curr.children.put(word.charAt(i), new PrefixTreeNode());
            }
            curr = curr.children.get(word.charAt(i));
        }
        curr.end = true;
        return true;
    }
}
class Solution {
    public String longestWord(String[] words) {
        //自动按照字典序排了
        Arrays.sort(words);
        PrefixTree tree=new PrefixTree();
        String currRes="";
        for (var word:words){
            if(tree.insert(word)){
                if (word.length()>currRes.length()){
                    currRes=word;
                }
            };
        }
        return currRes;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值