The fourth week of Leetcode problem brushing training

Posted by k994519 on Sun, 30 Jan 2022 13:39:24 +0100

array

  • Leetcode 119: Pascal's Triangle IIeasy
    • Key to problem solving:
      • Violent solution, construct pascal's triangle, find the row corresponding to rowIndex, and construct a List
        // Construct the logic of pascal's triangle. Note that the array length is rowIndex + 1
        int[][] triangle = new int[rowIndex + 1][rowIndex + 1]
        for (int i = 0; i < rowIndex + 1; i ++) {
          for (int j = 0; j <= i; j ++) {
            if (j == 0 || j == i) { 
              triangle[i][j] = 1;
            } else {
              // Defined according to pascal's triangle
              triangle[i][j] = triangle[i - 1][j - 1] + triangle[i][j - 1];
            }
          }
        }
        
  • Leetcode 915: Partition Array into Disjoint Intervalsmedium
    • Key to problem solving:
      • The key to this question is to find the maximum value of left side and ensure that any value of right side is greater than this value
      • At the same time, find the position with the smallest index in the array in the right side
      • Use [[greedy algorithm]]
          // Initialize two maximum values, one is the current maximum value of left side, and the other is the next maximum value that may occur to traverse the entire array
          // Initialize to the first value of the current array
          int currentMax = nums[0];
          int nextMax = nums[0];
          
          int ret = 0;
          
          // Traversal array
          for (int i = 1; i < nums.length; i ++) {
            int currentVal = nums[i];
            // If the current value is greater than nextMax, nextMax will be updated
            nextMax = Math.max(currentVal, nextMax);
            // If the current value is less than the current maximum value currentMax, record the current index and update the current maximum value on the left to nextMax
            if (currentVal < currentMax) {
              currentMax = nextMax;
              ret = i;
            }
          }
          // The current coordinate is the last index of left side, so ret + 1 should be returned
          return ret + 1
        
        

character string

  • Leetcode 20: Valid Parentheseseasy

    • Key to problem solving:
      • If it is true, case will be returned directly; if it is null, case will be returned directly
        if (s.length() == 0) return true;
        
      • 2. According to the meaning of the question, the adjacent () [] {} is valid. You can consider using the stack structure and the principle of last in first out. If you match the symbol into pair, you will pop the element. Finally, the stack will be cleared for legal characters
        for (char c: s.toCharArray()) {
          // If it is an open symbol, push it into the stack
          if (c == '(' || c == '[' || c == '{') {
            stack.push(c);
          } else {
            // If the stack is empty at this time but has not been traversed, it indicates that the next char may be one of '}]', which indicates that it is illegal and returns false
            if (stack.isEmpty()) {
              return false;
            }
            // If the next element is one of '}]', compare it with the element of the current stack
            if (c == ']' && stack.peek() != '[') {
                            return false;
                        } else if (c == '}' && stack.peek() != '{') {
                            return false;
                        } else if (c == ')' && stack.peek() != '(') {
                            return false;
                        }
                        // If false is not returned, it indicates that pair matching is successful. pop the element from the stack
                        stack.pop();
          }
        }
        return stack.isEmpty();
        
  • Leetcode 22: Generate Parenthesesmedium

    • Key to problem solving: Understanding [[backtracking]]
  • Leetcode 67: Add Binaryeasy

    • Key to problem solving:
      • To understand the meaning of the question is to convert the binary numbers of two strings into decimal, add them and then convert them into binary numbers
      • It should be noted that when the binary of a and B is very long, it will exceed the length of the default type (int, Integer). Therefore, consider using BigInteger type or handwritten binary to decimal
            StringBuilder ret = new StringBuilder();
            // index starts from the end
            int aIndex = a.length() - 1;
            int bIndex = b.length() - 1;
            int carry = 0;
            while (aIndex >= 0 || bIndex >= 0) {
                int sum = 0;
                if (aIndex >= 0) {
                    // change char to int
                    sum += a.charAt(aIndex) - '0';
                    aIndex --;
                }
                // the same to string b
                if (bIndex >= 0) {
                    sum += b.charAt(bIndex) - '0';
                    bIndex --;
                }
                sum += carry;
                ret.append(sum % 2);
                carry = sum / 2;
            }
            if (carry > 0) {
                ret.append(carry);
            }
            return ret.reverse().toString();
    
  • Leetcode 443: String Compressionmedium

    • Key to problem solving
      • This problem is solved by sliding window algorithm
        • 1. corner case judges that if the length is 1, it will be returned directly, because the number after the character with length of 1 does not need to be added

          int length = chars.length;
          if (length == 1) {
            return length;
          }
          
          
          
        • 2. Define the left and right boundaries of the window

          int left = 0;
          int right = 0;
          // i is a traversal index to facilitate in-place change. In combination with the meaning of the question, constant extra space is required
          int i = 0;
          	  
          
        • 3. Core logic

          	  // Based on the right boundary of the window
          	  while (right < length) {
          	      // Define a counter that holds the number of characters per character
          	      int count = 0;
          	      // Store characters for each window
          	      char c = chars[left];
          	      while (right < length && chars[right] == c) {
          	          // Traverse based on the right boundary of the window to calculate the window range
          	          count ++;
          	          right ++;
          	      }
          	  
          	      // in-place change
          	      chars[i] = c;
          	      // i index plus 1, that is, the last digit of the character is the count value
          	      i ++;
          	  
          	      // If count is greater than 1, you need to add a number after the character
          	      if (count > 1) {
          	          // If the count is greater than two digits, use the for loop to turn the number into char array, then change the positions in chars in turn, and i increases at the same time
          	          for (char character: Integer.toString(count).toCharArray()) {
          	              chars[i] = character;
          	              i ++;
          	          }
          	      }
          	      // When right traverses to the next character, the left boundary of the window will be updated, and a new window will be reopened to calculate the next group of characters
          	      left = right;
          	  }
          	  // Return the last i
          	  return i;
          
          
  • Leetcode 791: Custom Sort Stringmedium

    • Problem solving ideas
      • According to the meaning of the question, because the maximum length of the characters to be sorted is 200, and the element range is 26 English letters, based on this feature, the counting sorting algorithm can be used

        	// Create an array with a length of 26 to store the sorted character count
        	int[] tmp = new int[26];
        	for (char c: str.toCharArray()) {
        	    // Get the index position in the tmp array according to char -'a 'and count at the same time
        	    tmp[c - 'a'] ++;
        	}
        	// For example, if str is "abcddd", tmp is
        // [1, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        
        
        
      • Since the collation is specified according to the given character, the corresponding position of the character based on the collation is found in the tmp array, and the number of the character is calculated and decremented

        for (char c: order.toCharArray()) {
            while (tmp[c - 'a'] > 0) {
                sb.append(c);
            }
        }
        
      • The remaining characters are sorted alphabetically and inserted into StringBuilder

        for (int i = 0; i < 26; i ++) {
            while (tmp[i] -- > 0) {
                sb.append((char) (i + 'a'));
            }
        }
        

Topics: Algorithm Algorithms