Buckle questions 169, 171, 189, 198 and 202

Time:2021-2-22

Buckle questions 169, 171, 189, 198 and 202

169. Most elements

Buckle questions 169, 171, 189, 198 and 202

code:

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

171. Serial number of Excel table

How to solve the problem:

  • Tag: String traversal, decimal conversion
  • The initialization result is ans = 0. During traversal, each letter is subtracted from A. because a represents 1, after subtraction, each number needs to be added with 1 to calculate its representation
  • Num = letter -‘a ‘+ 1
  • Because there are 26 letters, it is equivalent to 26 base system, and every 26 numbers advance one bit
  • So for every bit traversed, ans = ans * 26 + num
  • Take ZY as an example, if Z is 26 and Y is 25, the result is 26 * 26 + 25 = 701
  • Time complexity: O (n)

code:

class Solution {
    public int titleToNumber(String s) {
        int ans = 0;
        for(int i=0;i<s.length();i++) {
            int num = s.charAt(i) - 'A' + 1;
            ans = ans * 26 + num;
        }
        return ans;
    }
}

189. Turn the array

Buckle questions 169, 171, 189, 198 and 202

The first idea is to solve the problem

The simplest way is to rotate the array K times, one element at a time.

Complexity analysis

Time complexity: O (n * k). Each element is moved one step o (n) k times o (k).

Space complexity: O (1). No extra space is used.

Code 1:

public class Solution {
    public void rotate(int[] nums, int k) {
        int temp, previous;
        for (int i = 0; i < k; i++) {
            previous = nums[nums.length - 1];
            for (int j = 0; j < nums.length; j++) {
                temp = nums[j];
                nums[j] = previous;
                previous = temp;
            }
        }
    }
}

The second idea is to solve the problem

We can use an extra array to put each element in the correct position, that is, the original array with the subscript i, we put it in the position of (I + k)% of the length of the array. Then copy the new array to the original one.

Code 2:

class Solution {
    public void rotate(int[] nums, int k) {
        int[] a=new int[nums.length];
        for(int i=0;i<nums.length;i++){
            a[(i+k)%nums.length]=nums[i];
        }
        for(int i=0;i<nums.length;i++){
            nums[i]=a[i];
        }
    }
}

198. Robbing homes

Question:

You are a professional thief, planning to steal houses along the street. There is a certain amount of cash hidden in each room. The only restricting factor for you to steal is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are intruded by thieves at the same night, the system will automatically alarm.

Given an array of non negative integers representing the amount of money stored in each house, calculate the maximum amount you can steal in one night without touching the alarm device.

Example 1:

Input: [1,2,3,1] output: 4 explanation: steal house 1 (amount = 1), then steal house 3 (amount = 3). The maximum amount of money stolen = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1] output: 12 explanation: steal house 1 (amount = 2), steal house 3 (amount = 9), and then steal house 5 (amount = 1). The maximum amount of money stolen = 2 + 9 + 1 = 12.

Tips:

0 <= nums.length <= 100 0 <= nums[i] <= 400

How to solve the problem:

Consider the simplest case first. If there is only one house, the maximum total amount can be obtained by stealing the house. If there are only two houses, because the two houses are adjacent to each other, they can not steal at the same time, only one of them can be stolen. Therefore, choosing the house with higher amount of money to steal can steal the maximum total amount.

1.If the number of houses is more than two, how to calculate the maximum total amount that can be stolen? For the K ~ (k > 2) house, there are two options

2.If you steal the kth house, you can’t steal the Kth-1 house. The total amount of theft is the sum of the maximum total amount of the first K-2 houses and the amount of the kth house.

The total amount of theft is the highest total amount of the first k-1 houses.

In the two options, choose the option with larger total amount of theft, and the total amount of theft corresponding to this option is the highest total amount that the top k houses can steal.

If DP [i] is used to represent the maximum total amount that can be stolen from the first I houses, then there is the following state transition equation:

dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]);

code:

class Solution {
    public int rob(int[] nums) {
        if(nums==null||nums.length==0){
            return 0;
        }
        int length=nums.length;
        if(length==1){
            return nums[0]; 
        }
        int[] dp=new int[length];
        dp[0]=nums[0];
        dp[1]=Math.max(nums[0],nums[1]);
        for(int i=2;i<length;i++){
            dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]);
        }
        return dp[length-1];
    }
}

202. Happy number

Question:

Write an algorithm to determine whether a number n is a happy number.

“Happy number” is defined as: for a positive integer, replace the number with the sum of squares of the numbers in each position each time, and then repeat the process until the number becomes 1, or it may be an infinite cycle but never becomes 1. If it can be changed to 1, then this number is the happy number.

If n is a happy number, it returns true; if n is not, it returns false.

Example:

Input: 19 output: true explanation: 12 + 92 = 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1

The first idea is to solve the problem

The algorithm is divided into two parts, we need to design and write code.

1.Given a number n, what is the next number?

2.According to a series of numbers to determine whether we have entered a cycle.

In the first part, we separate the digits and find the sum of squares.

Part 2 can be done with HashSet. Every time we generate the next number in the chain, we check whether it is already in the HashSet.

If it’s not in the HashSet, we should add it.

If it’s in a HashSet, that means we’re in a loop, so we should return false.

The reason we use hashsets instead of vectors, lists, or arrays is because we repeatedly check for the presence of a number. It takes O (1) to check whether the number is in the hash set, and O (n) for other data structures. Choosing the right data structure is the key to solve these problems.

The core idea is to use a HashSet and recursion. Through recursion, we can judge whether result 1 will appear in the end. Through HashSet, we can know whether it is a loop.

Code 1:

class Solution {

    private int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }

    public boolean isHappy(int n) {
        Set<Integer> seen = new HashSet<>();
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);
            n = getNext(n);
        }
        return n == 1;
    }
}

The second idea is to solve the problem

The principle is that we use two pointers, one is fast and the other is slow. If it is a happy number, then the fast pointer will reach the number 1 first, and it will end. If it is not a happy number, then the fast and slow pointers will finally meet on a certain number. In coding, we can make the fast pointer execute one more step each time, which is FAS tRunner = getNext(getNext(fastRunner));

Code 2:

class Solution {
    public int getNext(int n){
        int totalSum=0;
        while(n>0){
            int d=n%10;
            n=n/10;
            totalSum+=d*d;
        }
        return totalSum;
    }
    public boolean isHappy(int n) {
        int slowRunner=n;
        int fastRunner=getNext(n);
        while(fastRunner!=1&&slowRunner!=fastRunner){
            slowRunner=getNext(slowRunner);
            fastRunner=getNext(getNext(fastRunner));
        }
        return fastRunner==1;
    }
}

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]