算法刷题记录(LeetCode 121-150)

121. Best Time to Buy and Sell Stock(solved)

    public int maxProfit(int[] prices) {
        int[] res=new int[prices.length];
        int curr_max=0;
        for(int i=1;i<prices.length;i++){
            res[i]=Math.max(prices[i]-prices[i-1]+res[i-1],0);
            curr_max=Math.max(curr_max,res[i]);
        }
        return curr_max;

    }

122. Best Time to Buy and Sell Stock II(Solved)

    public int maxProfit(int[] prices) {
        int sum=0;
        int i=0;
        while(i<prices.length-1){
            sum+=Math.max(prices[i+1]-prices[i],0);
            i++;
        }
        return sum;
    }

123. Best Time to Buy and Sell Stock III

Initialize four variables for taking care of the first buy, first sell, second buy, second sell. Set first buy and second buy as INT_MIN and first and second sell as 0. This is to ensure to get profit from transactions. Iterate through the array and return the second sell as it will store maximum profit.

DP

    public int maxProfit(int[] prices) {
        int firstBuy = Integer.MIN_VALUE;
        int firstSell = 0;
        int secondBuy = Integer.MIN_VALUE;
        int secondSell = 0;
        for (int val : prices) {
            firstBuy=Math.max(firstBuy,-val);
            firstSell=Math.max(firstSell,firstBuy+val);
            secondBuy=Math.max(secondBuy,firstSell-val);
            secondSell=Math.max(secondSell,secondBuy+val);
        }
        return secondSell;
    }

124. Binary Tree Maximum Path Sum

关键在于是否允许节点分裂,分裂则两个子节点都计数,但是允许分裂的的路径只能是从当前出发作为根->子的路径。

class Solution {
    public static int max_sum = 0;
    public int maxPathSum(TreeNode root) {
        max_sum = root.val;//考虑边界条件
        dfs(root);
        return max_sum;
    }
    public int dfs(TreeNode root){
        if(root==null){
            return 0;
        }
        int left_max=dfs(root.left);
        int right_max=dfs(root.right);
        left_max=Math.max(0,left_max);
        right_max=Math.max(0,right_max);
        max_sum=Math.max(max_sum,root.val+left_max+right_max);
        return root.val+Math.max(left_max,right_max);

    }
}

125. Valid Palindrome (Solved)

    public boolean isPalindrome(String s) {
        var processedString =s.replaceAll("[^a-zA-Z0-9]","");
        processedString=processedString.toLowerCase();
        System.out.println(processedString);
        for (int i=0,j=processedString.length()-1;i<=j;i++,j--){
            if(processedString.charAt(i)!=processedString.charAt(j)){
                return false;
            }
        }
        return true;
    }

*127. Word Ladder

双向BFS

class Solution {
public:
    unordered_set<string> paths;

    int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
        paths = unordered_set<string>(wordList.begin(), wordList.end());
        paths.insert(beginWord);
        if (!paths.count(endWord)) {
            return 0;
        }
        unordered_map<string, int> source_map;
        unordered_map<string, int> target_map;
        deque<string> source_queue;
        deque<string> target_queue;
        source_queue.push_back(beginWord);
        target_queue.push_back(endWord);
        source_map[beginWord] = 0;
        target_map[endWord] = 0;
        while (!source_queue.empty() && !target_queue.empty()) {
            int res = -1;
            if (source_queue.size() < target_queue.size()) {
                res = update(source_queue, source_map, target_map);
            } else {
                res = update(target_queue, target_map, source_map);
            }
            if (res != -1) {
                return res;
            }
        }
        return 0;
    }

    int update(deque<string> &curr_deque, unordered_map<string, int> &local, unordered_map<string, int> &opposite) {
        int curr_size = curr_deque.size();
        while (curr_size > 0) {
            string str = curr_deque.front();
            curr_deque.pop_front();
            int currStep = local[str];
            string str_copy(str);
            for (int i = 0; i < str.size(); ++i) {
                char originChar = str[i];
                for (int j = 0; j < 26; ++j) {
                    char newChar = 'a' + j;
                    if (originChar == newChar) {
                        continue;
                    }
                    str[i] = newChar;
                    //可能需要更新距离
                    if (!paths.count(str)){
                        continue;
                    }
                    if (local.count(str)&&local[str]<=local[str_copy]+1){
                        continue;
                    }
                    if (opposite.count(str)) {
                        return opposite[str] + currStep + 2;
                    }
                    local[str] = currStep + 1;
                    curr_deque.push_back(str);
                }
                str[i] = originChar;

            }
            curr_size--;
        }
        return -1;
    }
};

128. Longest Consecutive Sequence

HashSet空间换时间

    public int longestConsecutive(int[] nums) {
        Set<Integer> numsSet=Arrays.stream(nums).boxed().collect(Collectors.toSet());
        int longest=0;
        int length=0;
        for(int n:nums){
            if(!numsSet.contains(n-1)){
                length=0;
                while(numsSet.contains(n+length)){
                    length++;
                    longest=Math.max(longest,length);
                }
            }
        }
        return longest;
    }

129. Sum Root to Leaf Numbers

class Solution {
    public int sumNumbers(TreeNode root) {
        return preorderTraverse(root,0);
    }
    public int preorderTraverse(TreeNode root,int curretSum){
        if(root==null){
            return 0;
        }
        curretSum=curretSum*10+root.val;
        if(root.left==null&&root.right==null){
            return curretSum;
        }
        return preorderTraverse(root.left,curretSum)+preorderTraverse(root.right,curretSum);
    }
}

130. Surrounded Regions

class Solution {
    public static int row;
    public static int column;
    public void solve(char[][] board) {
        row= board.length;
        column=board[0].length;
        boolean[][] visited=new boolean[row][column];
        for (int i=0;i<column-1;i++){
            backTrack(board,0,i,visited);
        }
        for (int j=0;j<row-1;j++){
            backTrack(board,j,column-1,visited);
        }
        for (int i=1;i<column;i++){
            backTrack(board,row-1,i,visited);
        }
        for (int j=1;j<row;j++){
            backTrack(board,j,0,visited);
        }
        for (int i=1;i<row-1;i++){
            for (int j=1;j<column-1;j++){
                if (!visited[i][j])
                board[i][j]='X';
            }
        }
    }
    public void backTrack(char[][] board,int x,int y,boolean[][] visited){
        if (x<0||x>=row||y<0||y>=column||board[x][y]=='X'||visited[x][y]){
            return;
        }
        visited[x][y]=true;
        backTrack(board,x+1,y,visited);
        backTrack(board,x,y+1,visited);
        backTrack(board,x-1,y,visited);
        backTrack(board,x,y-1,visited);
    }
}

131. Palindrome Partitioning

class Solution {
    public static List<List<String>> res=new ArrayList<>();
    public static String source;
    public List<List<String>> partition(String s) {
        res.clear();
        source=s;
        backTrack(0,new ArrayList<>());
        return res;
    }
    public void backTrack(int curr_idx,ArrayList<String> currString){
        if (curr_idx>=source.length()){
            List<String> currRes=new ArrayList<>(currString);
            res.add(currRes);
            return;
        }
        for (int i=curr_idx;i<source.length();i++){
            if (checkPalindrome(source.substring(curr_idx,i+1))){
                currString.add(source.substring(curr_idx,i+1));
                backTrack(i+1,currString);
                currString.remove(currString.size()-1);
            }
        }
    }
    public boolean checkPalindrome(String s){
        int i=0;
        int j=s.length()-1;
        while (i<j){
            if (s.charAt(i)!=s.charAt(j)){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

*132. Palindrome Partitioning II

    public int minCut(String s) {
        char[] source = s.toCharArray();
        boolean[][] palindromeMatrix = new boolean[source.length + 1][source.length + 1];
        for (int i = 1; i <= source.length; i++) {
            for (int j = i; j >= 1; j--) {
                if (i == j) {
                    palindromeMatrix[i][j] = true;
                } else {
                    if (source[i - 1] == source[j - 1]) {
                        if (i-j == 1 || palindromeMatrix[j + 1][i - 1]) {
                            palindromeMatrix[j][i] = true;
                        }
                    }
                }
            }
        }
        // cuts[r] 代表将 [1,r] 这一段分割成若干回文子串所需要的最小分割次数
        int[] cuts = new int[source.length + 1];
        for (int i = 1; i <= source.length; i++) {
            if (palindromeMatrix[1][i]) {
                cuts[i] = 0;
            } else {
                // 先设定一个最大分割次数(r 个字符最多消耗 r - 1 次分割)
                cuts[i] = i - 1;
                for (int j = 1; j <= i; j++) {
                    if (palindromeMatrix[j][i]){
                        cuts[i] = Math.min(cuts[i], cuts[j-1] + 1);
                    }
                }
            }
        }
        return cuts[source.length];
    }

*133. Clone Graph

class Solution {
    public static Node[] nodes=new Node[101];
    public Node cloneGraph(Node node) {
        Arrays.fill(nodes,null);
        return cloneGraphImpl(node);
    }
    public Node cloneGraphImpl(Node node){
        if (node==null){
            return null;
        }
        if (nodes[node.val]!=null){
            return nodes[node.val];
        }
        Node curr=new Node(node.val);
        nodes[curr.val]=curr;
        curr.neighbors=new ArrayList<>();
        for (Node n: node.neighbors){
            curr.neighbors.add(cloneGraphImpl(n));
        }
        return curr;
    }
}

135. Candy

greedy Source

    public int candy(int[] ratings) {
        int[] leftMinimal=new int[ratings.length];
        leftMinimal[0]=1;
        int[] rightMinimal=new int[ratings.length];
        rightMinimal[ratings.length-1]=1;
        int currCandies=1;
        for(int i=1;i<ratings.length;i++){
            if(ratings[i]>ratings[i-1]){
                currCandies++;
                leftMinimal[i]=currCandies;
            }
            else{
                leftMinimal[i]=1;
                currCandies=1;
            }
        }
        currCandies=1;
        for (int j=ratings.length-2;j>=0;j--){
            if(ratings[j]>ratings[j+1]){
                currCandies++;
                rightMinimal[j]=currCandies;
            }
            else{
                rightMinimal[j]=1;
                currCandies=1;
            }
        }
        int totalCandies=0;
        for (int i=0;i<ratings.length;i++){
            totalCandies+=Math.max(leftMinimal[i],rightMinimal[i]);
        }
        return totalCandies;
    }

136. Single Number

HashSet Space Complexity O ( n ) O(n) O(n)

    public int singleNumber(int[] nums) {
        HashSet<Integer> numsSet=new HashSet<>();
        for(int n:nums){
            if(!numsSet.contains(n)){
                numsSet.add(n);
            }
            else{
                numsSet.remove(n);
            }
        }
        for(int n:numsSet){
            return n;
        }
        return -1;
    }

Xor Computation


在这里插入图片描述

    public int singleNumber(int[] nums) {
        int front=1;
        int res=nums[0];
        while(front<nums.length){
            res=res^nums[front];
            front++;
        }
        return res;
    }

*137. Single Number II

Bit Computation

    public int singleNumber(int[] nums) {
        int ans=0;
        for (int i = 0;i<32;i++){
            int total=0;
            for (int num:nums){
                total+=(num>>i)&1;
            }
            ans|=(total%3)<<i;
        }
        return ans;
    }

138. Copy List with Random Pointer

要点:使用HashMap加快搜索,不要忘了null

    public Node copyRandomList(Node head) {
        HashMap<Node,Node> oldToCopy=new HashMap<>();
        oldToCopy.put(null,null);
        Node curr=head;
        while(curr!=null){
            oldToCopy.put(curr,new Node(curr.val));
            curr=curr.next;
        }
        curr=head;
        while(curr!=null){
            Node node=oldToCopy.get(curr);
            node.next=oldToCopy.get(curr.next);
            node.random=oldToCopy.get(curr.random);
            curr=curr.next;
        }
        return oldToCopy.get(head);
    }

*140. Word Break II

class Solution {
    public static String source;
    HashSet<String> dict = new HashSet<>();
    List<String> res=new ArrayList<>();
    public List<String> wordBreak(String s, List<String> wordDict) {
        source=s;
        res.clear();
        dict.clear();
        dict.addAll(wordDict);
        backTrack(0,new ArrayList<>());
        return res;

    }
    public void backTrack(int curr,ArrayList<String> currList){
        if (curr>=source.length()){
            res.add(String.join(" ", currList));
            return;
        }
        for (int i=curr;i<source.length();i++){
            if (dict.contains(source.substring(curr,i+1))){
                currList.add(source.substring(curr,i+1));
                backTrack(i+1,currList);
                currList.remove(currList.size()-1);
            }
        }
    }
}

143. Reorder List

class Solution {
    public void reorderList(ListNode head) {
        if(head==null){
            return ;
        }
        ListNode fast=head.next;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        ListNode secondPart=slow.next;
        ListNode tempA;
        ListNode tempB;
        slow.next=null;
        secondPart=reverseList(secondPart);
        ListNode firstPart=head;
        while(secondPart!=null){
            tempA=firstPart.next;
            tempB=secondPart.next;
            firstPart.next=secondPart;
            secondPart.next=tempA;
            firstPart=tempA;
            secondPart=tempB;
        }

    }
    public ListNode reverseList(ListNode head){
        if(head==null){
            return null;
        }
        ListNode dummy = new ListNode();
        dummy.next=head;
        ListNode prev=null;
        ListNode curr=head;
        ListNode next;
        while(curr!=null){
            next=curr.next;
            curr.next=prev;
            prev=curr;
            curr=next;
        }
        return prev;

    }
}

144. Binary Tree Preorder Traversal(Solved)

 */
class Solution {
    public static List<Integer> res=new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        res.clear();
        preorderTraversalmpl(root);
        return res;
    }
    public void preorderTraversalmpl(TreeNode root){
        if(root==null){
            return ;
        }
        res.add(root.val);
        preorderTraversalmpl(root.left);
        preorderTraversalmpl(root.right);
    }
}

145. Binary Tree Postorder Traversal(Solved)

class Solution {
    public static List<Integer> res =new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        res.clear();
        bfs(root);
        return res;
    }
    public void bfs(TreeNode root){
        if(root==null){
            return ;
        }
        bfs(root.left);
        bfs(root.right);
        res.add(root.val);
    }
}

146. LRU Cache

leetcode:Leetcode
youtube
Geeksforgeeks

147. Insertion Sort List

    public ListNode insertionSortList(ListNode head) {
        if (head==null){
            return null;
        }
        ListNode dummy=new ListNode(-10000);
        dummy.next=head;
        ListNode next=dummy.next;
        dummy.next=null;
        while (next!=null){
            ListNode target=dummy;
            while (target.next!=null&&target.next.val<next.val){
                target=target.next;
            }
            ListNode successor=target.next;
            target.next=next;
            ListNode nextNode=next.next;
            next.next=successor;
            next=nextNode;
        }
        return dummy.next;
    }

149. Max Points on a Line

    public int maxPoints(int[][] points) {
        int max=0;
        for (int i=0;i<points.length;i++){
            HashMap<Integer,Integer> slopes=new HashMap<>();
            int localMax=0;
            int samePoint=0;
            for (int j = i+1; j<points.length;j++){
                int deltaY=points[j][1]-points[i][1];
                int deltaX=points[j][0]-points[i][0];
                if (deltaY==0&&deltaX==0){
                    samePoint++;
                }
                else if (deltaX==0){
                    slopes.put(Integer.MAX_VALUE,slopes.getOrDefault(Integer.MAX_VALUE,0)+1);
                    localMax=Math.max(localMax,slopes.get(Integer.MAX_VALUE));
                }
                else{
                    double currSlope=(double)deltaY/deltaX ;
                    int slope= (int) Math.round(currSlope*100000);
                    slopes.put(slope,slopes.getOrDefault(slope,0)+1);
                    localMax=Math.max(localMax,slopes.get(slope));
                }
                localMax += samePoint;
                max=Math.max(localMax,max);
            }
        }
        return max+1;
    }

150. Evaluate Reverse Polish Notation

class Solution {
    public int evalRPN(String[] tokens) {
        int numPrev;
        int numCurr;
        Stack<Integer> nums=new Stack<>();
        for (String token : tokens) {
            if (!Character.isDigit(token.charAt(0)) && token.length() == 1) {
                int curr = nums.pop();
                int prev = nums.pop();
                nums.push(calculate(token.charAt(0), prev, curr));
            } else {
                nums.push(Integer.parseInt(token));
            }
        }
        return nums.peek();
    }
    public int calculate(char operator,int a,int b){
        return switch (operator){
            case '+' -> a+b;
            case '-' -> a-b;
            case '*' -> a*b;
            case '/' ->a/b;
            default -> -1;
        };
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值