算法刷题记录(LeetCode 1-30)

1. Two Sum(Solved)

    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> s=new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(!s.containsKey(target-nums[i])){
                s.put(nums[i],i);
            }
            else return(new int[]{s.get(target-nums[i]),i});
        }
        return null;

    }

2. Add Two Numbers(Solved)

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy =new ListNode();
        var curr=dummy;
        int hyper=0;
        while(true){
            if(l1==null){
                break;
            }
            if(l2==null){
                break;
            }
            var res=l1.val+l2.val+hyper;
            hyper=(int)res/10;
            l2.val=res%10;
            curr.next=l2;
            l1=l1.next;
            l2=l2.next;
            curr=curr.next;
        }
        while(l1!=null){
            var res_solo=l1.val+hyper;
            hyper=(int)res_solo/10;
            l1.val=res_solo%10;
            curr.next=l1;
            l1=l1.next;
            curr=curr.next;
        }
        while(l2!=null){
            var res_solo2=l2.val+hyper;
            hyper=(int)res_solo2/10;
            l2.val=res_solo2%10;
            curr.next=l2;
            l2=l2.next;
            curr=curr.next;
        }
        if(hyper>0){
           ListNode last=new ListNode(hyper);
           curr.next=last;
        }
        return dummy.next;
    }

3. Longest Substring Without Repeating Characters

Leetcode:leetcode
Geeksforgeeks
The idea is to use window sliding
Whenever we see repetition, we remove the previous occurrence and slide the window.

4. Median of Two Sorted Arrays

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int half=(int)(nums1.length+nums2.length)/2;
        int[] a,b;
        if(nums1.length>nums2.length){
            a=nums2;
            b=nums1;
        }
        else{
            a=nums1;
            b=nums2;
        }
        int len_a=a.length;
        int len_b=b.length;
        int i;
        int j;
        int left=0;
        int right=len_a-1;
        while(true){
         注意,这里python的实现代码为i(left+right)//2其效果等同于Math.floor而不是%;
            i= (int)Math.floor((double)(left+right)/2)            
            j=half-i-2;
            int left_a = i>=0 ? a[i]:Integer.MIN_VALUE;
            int right_a = (i+1)<len_a ? a[i+1]:Integer.MAX_VALUE;
            int left_b = j>=0? b[j]:Integer.MIN_VALUE;
            int right_b = (j+1)<len_b ? b[j+1]:Integer.MAX_VALUE;
            if((left_a<=right_b)&&(left_b<=right_a)){
                if((len_a+len_b)%2==0){
                    return (double)(Math.max(left_a,left_b)+Math.min(right_b,right_a))/2;
                }
                else{
                    return (double)Math.min(right_a,right_b);
                }
            }
            else if(left_a>right_b) {
                right=i-1;
            }
            else{
                left=i+1;
            } 

        }
    }

5. Longest Palindromic Substring

    public String longestPalindrome(String s) {
        String res_len="";
        int max_len=0;
        int len=s.length();
        for(int i=0;i<len;i++){
            int left=i,right=i;
            while(left>=0&&right<len&&s.charAt(left)==s.charAt(right)){
                if((right-left+1)>max_len){
                    max_len=right-left+1;
                    res_len=s.substring(left,right+1);
                }
                right++;
                left--;
            }
            left=i;
            right=i+1;
            while(left>=0&&right<len&&s.charAt(left)==s.charAt(right)){
                if((right-left+1)>max_len){
                    max_len=right-left+1;
                    res_len=s.substring(left,right+1);
                }
                right++;
                left--;
            }

        }
        return res_len;

    }
}

6. Zigzag Conversion(Solved)

注意每次到头时候的变化是-=2+=2

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        int i = 0;
        int j = 0;
        String[] res = new String[numRows];
        Arrays.fill(res,"");
        while (i < s.length()) {
            while (j < numRows) {
                if (i >= s.length()) {
                    break;
                }
                res[j] += s.charAt(i);
                i++;
                j++;
            }
            j-=2;
            while (j >= 0) {
                if (i >= s.length()) {
                    break;
                }
                res[j] += s.charAt(i);
                i++;
                j--;
            }
            j+=2;
        }
        StringBuilder resString = new StringBuilder();
        for (String ss : res) {
            resString.append(ss);
        }
        return resString.toString();
    }

7. Reverse Integer

    public int reverse(int x) {
        if (x == 0) {
            return 0;
        }
        boolean minus = x > 0 ? false : true;
        x = Math.abs(x);
        String original = Integer.valueOf(x).toString();
        String reversedString = new StringBuffer(original).reverse().toString();
        String MAX_INT = String.valueOf(Integer.MAX_VALUE);
        String MIN_INT = String.valueOf(Integer.MIN_VALUE);
        int startIdx = 0;
        if (reversedString.charAt(startIdx) == '0') {
            reversedString = reversedString.replace("^0+", "");
            if (minus) {
                reversedString = "-" + reversedString;
            }
            return Integer.parseInt(reversedString);
        }
        if (minus) {
            reversedString = "-" + reversedString;
            if(reversedString.length()<MIN_INT.length()){
                return Integer.parseInt(reversedString);
            }
            startIdx = 1;
            for (int i = startIdx; i < reversedString.length(); i++) {
                
                if (reversedString.charAt(i) < MIN_INT.charAt(i)) {
                    return Integer.parseInt(reversedString);
                } else if (reversedString.charAt(i) > MIN_INT.charAt(i)) {
                    return 0;
                }
            }
        }
        if(reversedString.length()<MAX_INT.length()){
            return Integer.parseInt(reversedString);
        }
        for (int i = startIdx; i < reversedString.length(); i++) {
            if (reversedString.charAt(i) < MAX_INT.charAt(i)) {
                return Integer.parseInt(reversedString);
            } else if (reversedString.charAt(i) > MAX_INT.charAt(i)) {
                return 0;
            }
        }
        return 0;
    }

8. String to Integer (atoi)

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.math.BigInteger;
class Solution {
    public int myAtoi(String s) {
        String regex="^\\s*[\\+\\-]?\\d+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher=pattern.matcher(s);
        if(matcher.find()==true){
            BigInteger currVal=new BigInteger(matcher.group().strip());
            BigInteger maxInt = new BigInteger(String.valueOf(Integer.MAX_VALUE));
            BigInteger minInt=new BigInteger(String.valueOf(Integer.MIN_VALUE));
            if(currVal.compareTo(maxInt)>0){
                return Integer.MAX_VALUE;
            }
            if(currVal.compareTo(minInt)<0){
                return Integer.MIN_VALUE;
            }
            System.out.println(matcher.group());
            System.out.println("true");
            return Integer.valueOf(matcher.group().strip());
        }
        else{
            System.out.println(" false result");
            return Integer.valueOf(0);
        }
    }
}

9. Palindrome Number

转string解法

    public boolean isPalindrome(int x) {
        if(x<0){
            return false;
        }
        String nums=String.valueOf(x);
        int start=0;
        int end=nums.length()-1;
        while (start<end){
            if(nums.charAt(start)!=nums.charAt(end)){
                return false;
            }
            start++;
            end--;
        }
        return true;
    }

非转string解法

    public boolean isPalindrome(int x) {
        if(x<0){
            return false;
        }
        if(x==0){
            return true;
        }
        if(x%10==0){
            return false;
        }
        long x_long =(long)x;
        long div=1;
        while (x_long>=10*div){
            div*=10;
        }
        while (x_long>0){
            long right = x_long%10;
            long left= x_long/div;
            if(left!=right){
                return false;
            }
            x_long=x_long%div/10;
            div/=100;
        }
        return true;
    }

10. Regular Expression Matching

bfs

class Solution {
    public static String curr_S;
    public static String curr_P;
    public boolean isMatch(String s, String p) {
        curr_S=s;
        curr_P=p;
        return bfs(0,0);

    }
    public boolean bfs(int i,int j){
        if(i>=curr_S.length()&&j>=curr_P.length()){
            return true;
        }
        if(j>=curr_P.length()){
            return false;
        }
        //与或运算优先级相同
        var match=i<curr_S.length()&&(curr_S.charAt(i)==curr_P.charAt(j)||curr_P.charAt(j)=='.');
        if(j+1<curr_P.length()&&curr_P.charAt(j+1)=='*'){
            return bfs(i,j+2) // 不使用*符号
            || (match&&bfs(i+1,j)); //使用*符号
        }
        if(match){
            return bfs(i+1,j+1);
        }
        return false;
    }
}

11. Container With Most Water

双栈

    public int maxArea(int[] height) {
        Deque<Integer> monotonic=new LinkedList<>();
        Deque<Integer> reverseMonotomic=new LinkedList<>();
        int i=0;
        while (i<height.length){
            while (!monotonic.isEmpty()&&i<height.length&&height[monotonic.peekLast()]>=height[i]){
                i++;
            }
            if(i>=height.length){
                break;
            }
            monotonic.addLast(i);
            i++;
        }
        int j=height.length-1;
        while (j>=0){
            while (!reverseMonotomic.isEmpty()&&j>=0&&height[reverseMonotomic.peekLast()]>=height[j]){
                j--;
            }
            if(j<0){
                break;
            }
            reverseMonotomic.addLast(j);
            j--;
        }
        int maxVolume=0;
        for(int l:monotonic){
            for(int r:reverseMonotomic){
                maxVolume=Math.max(Math.min(height[l],height[r])*(r-l),maxVolume);
            }
        }
        return maxVolume;
    }

双指针

    public int maxArea(int[] height) {
        int maxVolume=0;
        int left=0;
        int right=height.length-1;
        while (left<right){
            maxVolume=Math.max(maxVolume,Math.min(height[left],height[right])*(right-left));
            if(height[left]>height[right]){
                right--;
            }
            else{
                left++;
            }
        }
        return maxVolume;
    }

12. Integer to Roman

class Solution {
    public static final LinkedHashMap<Integer,String> alphabet=initAlphabet();
    public static final List<Integer> listKeys = new ArrayList<Integer>(alphabet.keySet());
    private static LinkedHashMap<Integer, String> initAlphabet() {
        LinkedHashMap<Integer, String> alphabet=new LinkedHashMap<>();
        alphabet.put(1,"I");
        alphabet.put(4,"IV");
        alphabet.put(5,"V");
        alphabet.put(9,"IX");
        alphabet.put(10,"X");
        alphabet.put(40,"XL");
        alphabet.put(50,"L");
        alphabet.put(90,"XC");
        alphabet.put(100,"C");
        alphabet.put(400,"CD");
        alphabet.put(500,"D");
        alphabet.put(900,"CM");
        alphabet.put(1000,"M");
        return alphabet;
    }

    public String intToRoman(int num) {
        StringBuilder res=new StringBuilder();
        for (int i=listKeys.size()-1;i>=0;i--){
            int val=listKeys.get(i);
            if(num/val>0){
                var count=num/val;
                res.append(alphabet.get(val).repeat(num/val));
                num=num%val;
            }
        }
        return res.toString();
    }
}

13. Roman to Integer

    public int romanToInt(String s) {
        int curr=0;
        HashMap<String,Integer> dict=new HashMap<>();
        dict.put("I",1);
        dict.put("V",5);
        dict.put("X",10);
        dict.put("L",50);
        dict.put("C",100);
        dict.put("D",500);
        dict.put("M",1000);
        dict.put("IV",4);
        dict.put("IX",9);
        dict.put("XL",40);
        dict.put("XC",90);
        dict.put("CD",400);
        dict.put("CM",900);
        String prev="";
        int res=0;
        while (curr<s.length()){
            prev+=s.charAt(curr);
            if (dict.containsKey(prev)){
            }
            else{
                res+=dict.get(prev.substring(0,prev.length()-1));
                prev= String.valueOf(s.charAt(curr));
            }
            curr++;
        }
        if (dict.containsKey(prev)){
            res+=dict.get(prev);
        }
        return res;
    }

14. Longest Common Prefix

    public String longestCommonPrefix(String[] strs) {
        int i=0;
        int strCounts=strs.length;
        int maxLen= Arrays.stream(strs).mapToInt(String::length).sorted().findFirst().orElse(-1);
        int res=0;
        while (i != maxLen) {
            for (int s = 1; s < strCounts; s++) {
                if (strs[s].charAt(i) != strs[s - 1].charAt(i)) {
                    return strs[0].substring(0, res);
                }
            }
            res++;
            i++;
        }
        return strs[0].substring(0,res);
    }

15. 3Sum

Geeksforgeeks

Approach

By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop.

Algorithm

  1. Sort the given array.
  2. Loop over the array and fix the first element of the possible triplet, arr[i].
  3. Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum,
    3.1. If the sum is smaller than the required sum, increment the first pointer.
    3.2. Else, If the sum is bigger, Decrease the end pointer to reduce the sum.
    3.3. Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.

Find all triplets with zero sum using Hashing

Geeksforgeeks

Approach

This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing.

Algorithm
  1. Create a Hashmap to store a key-value pair.
  2. Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1
  3. Check if the sum of ith and jth element multiplied with -1 is present in the Hashmap or not
  4. If the element is present in the Hashmap, print the triplet else insert the j’th element in the Hashmap.

16. 3Sum Closest

Fast

  1. Sort the given array.
  2. Loop over the array and fix the first element of the possible triplet, arr[i].
  3. Then fix two pointers, one at I + 1 and the other at n – 1. And look at the sum,
    • If the sum is smaller than the sum we need to get to, we increase the first pointer.
    • Else, If the sum is bigger, Decrease the end pointer to reduce the sum.
    • Update the closest sum found so far.
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res=0;
        int curr_Closest=Integer.MAX_VALUE;
        for(int i=0;i<nums.length-2;i++){
            int curr_target=target-nums[i];
            int left=i+1;
            int right=nums.length-1;
            while (left<right){
                int gap=curr_target-nums[left]-nums[right];
                if (Math.abs(gap)<Math.abs(curr_Closest)){
                    curr_Closest=gap;
                    res=nums[i]+nums[left]+nums[right];
                }
                if (gap<0){
                    right--;
                }
                else {
                    left++;
                }
            }

        }
        return res;
    }

17. Letter Combinations of a Phone Number

    public static final HashMap<Integer,List<Character>> PHONE_ALPHA=initPhoneAlpha();
    public static List<String> res=new ArrayList<>();
    private static HashMap<Integer, List<Character>> initPhoneAlpha() {
        HashMap<Integer, List<Character>> phoneAlpha=new HashMap<>();
        phoneAlpha.put(2,List.of('a','b','c'));
        phoneAlpha.put(3,List.of('d','e','f'));
        phoneAlpha.put(4,List.of('g','h','i'));
        phoneAlpha.put(5,List.of('j','k','l'));
        phoneAlpha.put(6,List.of('m','n','o'));
        phoneAlpha.put(7,List.of('p','q','r','s'));
        phoneAlpha.put(8,List.of('t','u','v'));
        phoneAlpha.put(9,List.of('w','x','y','z'));
        return phoneAlpha;

    }
    public List<String> letterCombinations(String digits) {
        res.clear();
        if(digits.isEmpty()){
            return res;
        }
        backTrack(digits,0,new ArrayList<>());
        return res;
    }
    public void  backTrack(String digits,int idx,ArrayList<Character> currRes){
        if(idx==digits.length()){
            res.add(currRes.stream().map(String::valueOf).collect(Collectors.joining()));
            return;
        }
        int num=Character.getNumericValue(digits.charAt(idx));
        for (Character c:PHONE_ALPHA.get(num)){
            currRes.add(c);
            backTrack(digits,idx+1,currRes);
            currRes.remove(currRes.size()-1);
        }
    }

18. 4Sum

class Solution {
    public static List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> fourSum(int[] nums, int target) {
        res.clear();
        Arrays.sort(nums);
        long long_target=(long) target;
        kSum(4,0,target,nums,new Stack<>());
        return res;
    }
    public void kSum(int k,int start,long target,int[] nums,Stack<Integer> quad){
        if (k>2){
            for(int i=start;i+k<=nums.length;i++){
                if(i>start&&nums[i]==nums[i-1]){
                    continue;
                }
                quad.push(nums[i]);
                kSum(k-1,i+1,target-nums[i],nums,quad);
                quad.pop();
            }
            return;
        }
        int left=start,right=nums.length-1;
        while(left<right){
            long sum=nums[left]+nums[right];
            if(sum<(long)target){
                left++;
            }
            else if(sum>target){
                right--;
            }
            else{
                var currRes= new ArrayList<>(quad.stream().toList());
                currRes.add(nums[left]);
                currRes.add(nums[right]);
                res.add(currRes);
                left++;
                while (left<right&&nums[left]==nums[left-1]){
                    left++;
                }
            }
        }
    }
}

19. Remove Nth Node From End of List

    public ListNode removeNthFromEnd(ListNode head, int n) {
        var fast=head;
        var curr=head;
        ListNode dummy=new ListNode();
        dummy.next=head;
        ListNode prev=null;
        if(head.next==null){
            return null;
        }
        for (int i=0;i<n;i++){
            fast=fast.next;
        }
        if(fast==null){
            return dummy.next.next;
        }
        System.out.println(fast.val);
        while(fast!=null){
            prev=curr;
            fast=fast.next;
            curr=curr.next;
        }
        System.out.println(prev.val);
        prev.next=prev.next.next;
        return dummy.next;
    }

20. Valid Parentheses

class Solution {
    public boolean isValid(String s) {
        Stack<Character> parenthesis=new Stack<Character>();
        if(s==null||s.isEmpty()){
            return true;
        }
        parenthesis.push(s.charAt(0));
        for (int j=1;j<s.length();j++){
            if(parenthesis.isEmpty()){
                parenthesis.push(s.charAt(j));
                continue;
            }
            var top=parenthesis.peek();
            if (match(top,s.charAt(j))){
                parenthesis.pop();
            }
            else{
                parenthesis.push(s.charAt(j));
            }
        }
        return parenthesis.isEmpty();

    }
    public boolean match(char p,char q){
        switch (p){
            case '(':
                if (q!=')')
                {
                    return false;
                }
                else return true;
            case '{':
                if (q!='}')
                {
                    return false;
                }
                else return true;
            case '[':
                if (q!=']')
                {
                    return false;
                }
                else return true;
            
                
        }
        return false;
    }    
}

21.Merge Two Sorted Lists

Geeksforgeeks

22. Generate Parentheses

Leetcode:Generate Parentheses

    public List<String> generateParenthesis(int n) {
        Stack<Character> charStack =new Stack<>();
        List<String> res=new ArrayList<>();    
        backtrack(charStack,res,0,0,n);  
        return res;
        
    }
    public void backtrack(Stack<Character> charStack,List<String> res,int leftCount,int rightCount,int n){
        if(leftCount==rightCount&&rightCount==n){
            String resString = Arrays.stream(charStack.toArray(Character[]::new))
                .map(ch -> ch.toString())
                .collect(Collectors.joining());
            res.add(resString);
            return;
        }
        if(leftCount<n){
            charStack.push('(');
            backtrack(charStack,res,leftCount+1,rightCount,n);
            charStack.pop();
        }
        if(rightCount<leftCount){
            charStack.push(')');
            backtrack(charStack,res,leftCount,rightCount+1,n);
            charStack.pop();
        }

    }

23. Merge k Sorted Lists

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length==0){
            return null;
        }
        List<ListNode> convertedList=Arrays.asList(lists);
        // System.out.println("converted "+convertedList.get(1));
        while(convertedList.size()>1){
            List<ListNode> mergedList=new ArrayList<>();
            for(int i=0;i<convertedList.size();i+=2){
                ListNode l1=convertedList.get(i);
                ListNode l2;
                if(i+1<convertedList.size()){
                    l2=convertedList.get(i+1);
                }
                else {
                    l2=null;
                }
                System.out.print("l1 "+l1+" l2 "+l2);
                System.out.println();
                ListNode res=mergeList(l1,l2);
                System.out.println("res "+res);
                mergedList.add(res);
            }
            System.out.println(mergedList.size());
            System.out.println(mergedList.get(0));
            convertedList=mergedList;
            
        }
        return convertedList.get(0);

    }
    public ListNode mergeList (ListNode l1,ListNode l2){
        ListNode dummy = new ListNode();
        ListNode tail= dummy;
        while(l1!=null&&l2!=null){
            if(l1.val<l2.val){
                tail.next=l1;
                l1=l1.next;
                tail=tail.next;
            }
            else{
                tail.next=l2;
                l2=l2.next;
                tail=tail.next;
            }


        }
        if(l1!=null){
            tail.next=l1;
        }
        if(l2!=null){
            tail.next=l2;
        }
        
        return dummy.next;
    }
}

24. Swap Nodes in Pairs

    public ListNode swapPairs(ListNode head) {
        ListNode dummy=new ListNode();
        dummy.next=head;
        ListNode prev=dummy;
        ListNode curr=head;
        while(curr!=null&&curr.next!=null){
            // preserve the next pairs
            ListNode nextPair=curr.next.next;
            // swap
            ListNode second=curr.next;
            second.next=curr;
            curr.next=nextPair;
            prev.next=second;
            // change to the next pair
            prev=curr;
            curr=nextPair;
        }
        return dummy.next;
    }

25. Reverse Nodes in k-Group

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy=new ListNode(-1);
        dummy.next=head;
        ListNode groupPrev=dummy;

        while (true){
            ListNode kth=getKthNode(groupPrev,k);
            if(kth==null){
                break;
            }
            ListNode groupNext=kth.next;
            ListNode prev=kth.next;
            ListNode curr=groupPrev.next;
            while (curr!=groupNext){
                ListNode next=curr.next;
                curr.next=prev;
                prev=curr;
                curr=next;
            }
            ListNode tmp=groupPrev.next;
            groupPrev.next=kth;
            groupPrev=tmp;
        }
        return dummy.next;

    }
    public ListNode getKthNode(ListNode head,int k){
        while (head!=null&&k>0){
            head=head.next;
            k--;
        }
        return head;
    }

26. Remove Duplicates from Sorted Array(Solved)

    public int removeDuplicates(int[] nums) {
        int i = 1;
        int j = 1;
        while (j < nums.length) {
            if (nums[j] != nums[i - 1]) {
                var temp = nums[i];
                nums[i] = nums[j];
                nums[j] = nums[i];
                i++;
                j++;
            } else {
                j++;
            }
        }
    return i;
    }

27. Remove Element

    public int removeElement(int[] nums, int val) {
        int left=0;
        int right=nums.length-1;
        while (left<=right){
            if (nums[left]==val){
                int tmp=nums[left];
                nums[left]=nums[right];
                nums[right]=tmp;
                right--;
            }
            else {
                left++;
            }
        }
        return left;
    }

28. Find the Index of the First Occurrence in a String

class Solution {
    public int strStr(String haystack, String needle) {
        return SundaySearchAlgorithm(haystack.toCharArray(), needle.toCharArray());
    }

    public int SundaySearchAlgorithm(char[] haystack, char[] needle) {
        HashMap<Character, Integer> offset = new HashMap<>();
        for (int i = 0; i < needle.length; i++) {
            offset.put(needle[i], needle.length - i);
        }
        int curr = 0;
        String target = new String(needle);
        while (curr + needle.length <= haystack.length) {
            String sub = new String(haystack, curr, needle.length);
            if (sub.equals(target)) {
                return curr;
            } else {
                if (curr+ needle.length>=haystack.length){
                    return -1;
                }
                if (!offset.containsKey(haystack[curr + needle.length])) {
                    curr = curr + needle.length ;
                }
                else {
                    curr =curr+offset.get(haystack[curr + needle.length]);
                }
            }
        }
        return -1;

    }
}

30. Substring with Concatenation of All Words

    public List<Integer> findSubstring(String s, String[] words) {
        HashMap<String,Integer>alphabet=new HashMap<>();
        List<Integer> res=new ArrayList<>();
        for (var word:words){
            alphabet.put(word,alphabet.getOrDefault(word,0)+1);
        }
        int single_word_length=words[0].length();
        int words_count=words.length;
        for (int i=0;i+single_word_length<=s.length();i++){
            int frequency= words_count;
            HashMap<String,Integer> curr_alphabet= (HashMap<String, Integer>) alphabet.clone();
            for(int j=i;j+single_word_length<=s.length();j+=single_word_length){
                var word=s.substring(j,j+single_word_length);
                if(!curr_alphabet.containsKey(word)||curr_alphabet.get(word)==0){
                    break;
                }
                frequency--;
                if(frequency==0){
                    res.add(i);
                    break;
                }
                curr_alphabet.put(word,curr_alphabet.get(word)-1);
            }
        }
        return res;
    }

200.Number of Islands

This is a variation of the standard problem: “Counting the number of connected components in an undirected graph”

Finding the number of islands using DFS

思路

运用DFS,将所有有1的岛屿缩小的大小为1

Algorithm

Follow the steps below to solve the problem:

  • Initialize count = 0, to store the answer.
  • Traverse a loop from 0 till ROW
    • Traverse a nested loop from 0 to COL
      • If the value of the current cell in the given matrix is 1
        • Increment count by 1
        • Call DFS function
          • If the cell exceeds the boundary or the value at the current cell is 0
            • Return.
          • Update the value at the current cell as 0.
          • Call DFS on the neighbor recursively
  • Return count as the final answer.

151.Reverse Words in a String

    public String reverseWords(String s) {
        String[] splitedStrings=s.split("\\s+");
        String res="";
        for(int i=splitedStrings.length-1;i>=0;i--){
            res=res+splitedStrings[i]+" ";
        }
        return res.strip();
    }

152. Maximum Product Subarray

    public int maxProduct(int[] nums) {
        int res = Arrays.stream(nums).max().getAsInt();
        int min=1;
        int max=1;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==0){
                min=1;
                max=1;
                continue;
            }
            int tmp_max=max*nums[i];
            int tmp_min=min*nums[i];
            max=Math.max(Math.max(tmp_max,tmp_min),nums[i]);
            min=Math.min(Math.min(tmp_max,tmp_min),nums[i]);
            res=Math.max(res,max);
        }
        return res;
    }

153. Find Minimum in Rotated Sorted Array

    public int findMin(int[] nums) {
        int left=0;
        int right=nums.length-1;
        int mid;
        if(nums[left]<=nums[right]){
            return nums[left];
        }
        while(left<right){
            mid=(left+right)>>1;
            if(mid-1>=0&&nums[mid-1]>nums[mid]){
                return nums[mid];
            }
            if(mid+1<nums.length&&nums[mid]>nums[mid+1]){
                return nums[mid+1];
            }
            if(nums[mid]<nums[right]){
                right=mid+1;
            }
            else{
                left=mid+1;
            }
        }
        return -1;
    }

155. Min Stack

class MinStack {
    public Stack<Integer> valueStack=new Stack<>();
    public Stack<Integer> minValueStack=new Stack<>();
    public MinStack() {

    }
    
    public void push(int val) {
        valueStack.push(val);
        if(minValueStack.isEmpty()){
            minValueStack.push(val);
        }
        else{
            minValueStack.push(Math.min(val,minValueStack.peek()));
        }
        
    }
    
    public void pop() {
        valueStack.pop();
        minValueStack.pop();
    }
    
    public int top() {
        return valueStack.peek();
    }
    
    public int getMin() {
        return minValueStack.peek();

    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

162. Find Peak Element

复杂解法,最大堆

    public int findPeakElement(int[] nums) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        for(int n:nums){
            maxHeap.offer(n);
        }
        return IntStream.range(0,nums.length).filter(i->nums[i]==maxHeap.peek()).findFirst().orElse(-1);
    }

Binary Search

Using Binary Search, check if the middle element is the peak element or not. If the middle element is not the peak element, then check if the element on the right side is greater than the middle element then there is always a peak element on the right side. If the element on the left side is greater than the middle element then there is always a peak element on the left side.

    public int findPeakElement(int[] nums) {
        if(nums.length==1){
            return 0;
        }
        if(nums.length==2){
            if(nums[0]>nums[1]){
                return 0;
            }
            else{
                return 1;
            }
        }
        int leftMost=0;
        int rightMost=nums.length-1;
        int left=0;
        int right=nums.length-1;
        int mid=0;
        int greatest;
        while(left<=right){
            mid=(left+right)>>1;
            if(mid==rightMost){
                if(nums[mid]>nums[mid-1]){
                    return mid;
                }
                else{
                    return mid-1;
                }
            }
            if(mid==leftMost){
                if(nums[mid]>nums[mid+1]){
                    return mid;
                }
                else{
                    return mid+1;
                }
            }
            greatest=Math.max(Math.max(nums[mid-1],nums[mid+1]),nums[mid]);
            if(greatest==nums[mid]){
                return mid;
            }
            else if(greatest==nums[mid+1]){
                left=mid+1;
            }
            else{
                right=mid-1;
            }
        }
        System.out.println(left);
        if(left==0){
            return 0;
        }
        return nums.length-1;
    }

165. Compare Version Numbers

    public int compareVersion(String version1, String version2) {
        String[] spiltedVersion1=version1.split("\\.");
        String[] spiltedVersion2=version2.split("\\.");
        int minLength=Math.min(spiltedVersion1.length,spiltedVersion2.length);
        for(int i=0;i<minLength;i++){
            if(Float.parseFloat(spiltedVersion1[i])>Float.parseFloat(spiltedVersion2[i])){
                return 1;
            }
            else if(Float.parseFloat(spiltedVersion1[i])<Float.parseFloat(spiltedVersion2[i])){
                return -1;
            }
        }
        if(spiltedVersion1.length==spiltedVersion2.length){
            return 0;
        }
        else if(spiltedVersion1.length>spiltedVersion2.length){
            for(int i=minLength;i<spiltedVersion1.length;i++){
                if(Float.parseFloat(spiltedVersion1[i])>0){
                    return 1;
                }
            }
            return 0;
        }
        else {
            for(int i=minLength;i<spiltedVersion2.length;i++){
                if(Float.parseFloat(spiltedVersion2[i])>0){
                    return -1;
                }
            }
            return 0;

        }
    }

168. Excel Sheet Column Title(Solved)

    public String convertToTitle(int columnNumber) {
        StringBuilder res = new StringBuilder();
        int extraCarry=0;
        while (columnNumber >26) {
            char residual_char = (char) ('A'+ (columnNumber-1) % 26);
            extraCarry=0;
            if(columnNumber%26==0){
                extraCarry=1;
            }
            columnNumber=columnNumber/26-extraCarry;
            res.append(residual_char);
        }
        char residual_char= (char) ('A'+(columnNumber-1)%26);
        res.append(residual_char);
        return res.reverse().toString();
    }

169. Majority Element

    public int majorityElement(int[] nums) {
        int count=0;
        int currentMajority=Integer.MAX_VALUE;
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=currentMajority){
                if(count==0){
                    currentMajority=nums[i];
                    count=1;
                }
                else{
                    count--;
                }
            }
            else{
                count++;
            }
        }
        return currentMajority;
    }

179. Largest Number

    public String largestNumber(int[] nums) {
        String res= Arrays.stream(nums).boxed().sorted((n1,n2)->{
                    String s1 =n1.toString();
                    String s2 =n2.toString();
                    String res1=s1+s2;
                    String res2=s2+s1;
                    for(int i=0;i<res1.length();i++){
                        if(res1.charAt(i)>res2.charAt(i)){
                            return -1;
                        }
                        else if (res1.charAt(i)<res2.charAt(i)){
                            return 1;
                        }
                    }
                    return -1;
                }).map(Object::toString).collect(Collectors.joining());
        res=res.replaceAll("^0+(.+)","$1");
        return res;
    }

189. Rotate Array

class Solution {
    public void rotate(int[] nums, int k) {
        k=k%nums.length;
        if(k==0){
            return;
        }
        reverse(nums,0,nums.length-1);
        reverse(nums,0,k-1);
        reverse(nums,k,nums.length-1);
    }
    public void reverse(int[] nums,int begin,int end){
        while (begin<end){
            int tmp=nums[begin];
            nums[begin]=nums[end];
            nums[end]=tmp;
            end--;
            begin++;
        }
    }
}

198. House Robber

youtube(强烈推荐查看neetcode讲解)

    public int rob(int[] nums) {
        int rob1=0;
        int rob2=0;
        int tmp=0;
        // [rob1,rob2,n,n+1...]
        for(int n:nums){
            tmp=Math.max(n+rob1,rob2);
            rob1=rob2;
            rob2=tmp;
        }
        return tmp;
    }

199. Binary Tree Right Side View(Solved)

层序遍历解法

class Solution {
    public static List<Integer> res=new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        res.clear();
        rightViewImpl(root);
        return res;
    }
    public void rightViewImpl(TreeNode root){
        if(root==null){
            return ;
        }
        Queue<TreeNode> tmp1=new LinkedList<>();
        int last=0;
        tmp1.add(root);
        while(tmp1.size()>0){
            Queue<TreeNode> tmp2=new LinkedList<>();
            while(tmp1.size()>0){
                TreeNode node=tmp1.poll();
                last=node.val;
                if(node.left!=null){
                    tmp2.add(node.left);
                 }
                if(node.right!=null){
                    tmp2.add(node.right);
                }
            }
            tmp1.clear();
            res.add(last);
            tmp1.addAll(tmp2);           
        }
    }
}

415. Add Strings(Solved)

    public String addStrings(String num1, String num2) {
        String res="";
        int carrying=0;
        String n1;
        String n2;
        // keep n1 longgest
        if(num2.length()>num1.length()){
            n1=num2;
            n2=num1;
        }
        else{
            n1=num1;
            n2=num2;
        }
        for(int i=n1.length()-1,j=n2.length()-1;j>=0;j--,i--){
            int resInt=Character.getNumericValue(n1.charAt(i))+Character.getNumericValue(n2.charAt(j))+carrying;
            carrying=resInt/10;
            res=resInt%10+res;
            
        }
        for(int i=n1.length()-n2.length()-1;i>=0;i--){
            int resInt =Character.getNumericValue(n1.charAt(i))+carrying;
            carrying=resInt/10;
            res=resInt%10+res;
        }
        if(carrying>0){
            return"1"+res;
        }
        return res;
    }

470. Implement Rand10() Using Rand7()

在这里插入图片描述

/**
 * The rand7() API is already defined in the parent class SolBase.
 * public int rand7();
 * @return a random integer in the range 1 to 7
 */
class Solution extends SolBase {
    public int rand10() {
        int rand=(rand7()-1)*7+rand7();
        while(rand>40){
            rand=(rand7()-1)*7+rand7();
        }
        return rand%10+1;
    }
}

字节跳动面试部分

万万没想到之抓捕孔连顺

 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        int d = in.nextInt();
        Integer[] distances = new Integer[n];
        distances[0] = in.nextInt();
        distances[1] = in.nextInt();
        long res = 0;
        for (int i = 2, j = 0; i < n; i++) {
            distances[i] = in.nextInt();
            while (distances[i] - distances[j] > d) {
                j++;
            }
            res += (long)(i - j) * (i - j - 1) / 2;
            res = res % 99997867;
        }
        System.out.print(res);
    }

Sort Colors/Dutch Flags

占用3空间解法

    public void sortColors(int[] nums) {
        int zeros=0;
        int ones=0;
        int twos=0;
        for(int num :nums){
            switch(num){
                case 0 -> zeros++;
                case 1 -> ones++;
                case 2 -> twos++;
            }
        }
        for(int i=0;i<nums.length;i++){
            if(zeros>0){
                nums[i]=0;
                zeros--;
            }
            else if(ones>0){
                nums[i]=1;
                ones--;
            }
            else{
                nums[i]=2;
            }
        }
    }

占用1空间解法

    public void sortColors(int[] nums) {
        int left=0,i=0,right=nums.length-1;
        int temp;
        while(i<=right){
            if(nums[i]==0){
                temp=nums[i];
                nums[i]=nums[left];
                nums[left]=temp;
                left++;
            }
            else if(nums[i]==2){
                temp=nums[right];
                nums[right]=nums[i];
                nums[i]=temp;
                right--;
                i--;
            }
            i++;            
        }
    }

NowCoder补充

1.字节跳动高频题——排序奇升偶降链表Source

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode sortLinkedList (ListNode head) {
        ListNode[] departed = departLinkedList(head);
        ListNode assending = departed[0];
        ListNode desending = departed[1];
        ListNode reversedDesending = reverse(desending);
        // write code here
        return merge(assending,reversedDesending);
    }
    public ListNode[] departLinkedList(ListNode head) {

        ListNode listA = head;
        ListNode listACurr = listA;
        ListNode listB = head.next;
        ListNode listBCurr = listB;
        ListNode curr = listB;
        if (listB != null) {
            curr = listB.next;
        } else {
            return new ListNode[] {head, null};
        }
        while (curr != null) {
            listACurr.next = curr;
            listACurr = listACurr.next;
            curr = curr.next;
            if (curr == null) {
                listBCurr.next = null;
                break;
            } else {
                listBCurr.next = curr;
                listBCurr = listBCurr.next;
                curr = curr.next;
            }
        }
        listACurr.next = null;
        return new ListNode[] {listA, listB};
    }
    public ListNode reverse(ListNode head) {
        ListNode curr = head;
        ListNode prev = null;
        ListNode next;
        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    public ListNode merge(ListNode headA, ListNode headB) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (headA != null && headB != null) {
            if (headA.val < headB.val) {
                tail.next = headA;
                headA = headA.next;
                tail = tail.next;
            } else {
                tail.next = headB;
                headB = headB.next;
                tail = tail.next;
            }
        }
        if (headA != null) {
            tail.next = headA;
        }
        if (headB != null) {
            tail.next = headB;
        }
        return dummy.next;
    }
}

2. 字节跳动高频题——圆环回原点问题Source

    public int circle (int n) {
        int length = 10;
        int[][] dp = new int[n + 1][length];
        dp[0][0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < length; j++) {
                dp[i][j] = dp[i - 1][(j - 1 + length) % length] % 1000000007 + dp[i - 1][(j + 1)
                           % length] % 1000000007;
            }
        }
        return dp[n][0] % 1000000007;
    }

9. 字节高频题补充——36进制加法 Source

class Solution:
    def thirtysixAdd(self, A: str, B: str) -> str:
        i = max(len(A), len(B)) - 1
        idx_a = len(A) - 1
        idx_b = len(B) - 1
        carry = 0
        res_str = list()
        while i >= 0:
            val_A = self.char_2_int(A[idx_a]) if idx_a >= 0 else 0
            val_B = self.char_2_int(B[idx_b]) if idx_b >= 0 else 0
            res = carry + val_A + val_B
            residual = res % 36
            carry = res // 36
            i -= 1
            idx_a -= 1
            idx_b -= 1
            # write code here
            res_str.append(self.int_2_char(residual))
        if carry:
            res_str.append("1")
        res_str.reverse()
        return "".join(res_str)

    @staticmethod
    def char_2_int(ch) -> int:
        if ord(ch) > ord("9"):
            return 10 + ord(ch) - ord("a")
        else:
            return ord(ch) - ord("0")

    @staticmethod
    def int_2_char(int_num) -> str:
        if int_num <= 9:
            return str(int_num)
        else:
            return chr(int_num - 10 + ord("a"))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值