Sword Pointer Offer (Special Assault Edition) Question 3|4

Preface

  • Now that the front-end requirements have become higher, you may encounter algorithm questions when looking for a job. Be prepared by brushing a few algorithm questions every day. Today is question 3|4 of "Sword Finger Offer (Special Assault Edition)".

Sword refers to Offer II 003. The number of 1's in the binary system of the first n numbers.

Given a non-negative integer n, count the number of 1's in the binary representation of each number between 0 and n and output an array.

Difficulty: Easy

示例 1:
输入: n = 2 输出: [0,1,1] 解释:  0 --> 0 1 --> 1 2 --> 10 
示例 2:
输入: n = 5 输出: [0,1,1,2,1,2] 解释: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 

说明 :
● 0 <= n <= 105

Knowledge point: Bit operation  dynamic programming

Method 1: Bit operations

analyze:

Intuitive solution, use a for loop to count the number of 1's in the binary form of each integer i from 0 to n.

Use "i&(i-1)" each time to change the rightmost 1 of integer i into 0. If 1 is subtracted from integer i, then its rightmost 1 becomes 0. If there are 0s to the right, all the 0s to the right become 1s, while all the bits to the left remain unchanged.

 * @param {number} n
 * @return {number[]}
 */
var countBits = function(n) {
    let result = new Array(n + 1).fill(0);;
    for (let i = 0; i<=n; i++) {
        let j = i;
        while(j !== 0) {
            result[i]++;
            j = j & (j -1);
        }
    }
    return result;
};

Complexity analysis

  • Time complexity: O(nlog⁡n). It is necessary to calculate "one-bit number" for each integer from 0 to n. The time for calculating "one-bit number" for each integer will not exceed O(log⁡n).

  • Space complexity: O(1). The space complexity is constant except for the returned array.

Method 2: Dynamic programming

analyze:

According to the previous analysis, "i&(i-1)" changes the rightmost 1 in the binary form of i into 0. That is to say, the number of 1's in the binary form of the integer i is greater than "i&(i-1)" The number of 1's in the binary form of " is 1 more.

 * @param {number} n
 * @return {number[]}
 */
var countBits = function(n) {
    let res = [];
    res[0] = 0
    for(let i = 1;i <=n;i++) {
        
        res[i] = res[i & (i - 1)] + 1;
    }
    return res
};

Complexity analysis

  • Time complexity: O(n). For each integer, it only takes O(1) time to calculate the "one-bit number".

  • Space complexity: O(1). The space complexity is constant except for the returned array.

Sword Points Offer II 004. A number that only appears once

You are given an integer array nums. Except for an element that appears only once , each element appears exactly three times. Please find and return the element that appears only once.

Difficulty: Moderate

示例 1:
输入:nums = [2,2,3,2] 输出:3 
示例 2:
输入:nums = [0,1,0,1,0,1,100] 输出:100 

提示:
● 1 <= nums.length <= 3 * 104
● -231 <= nums[i] <= 231 - 1
● nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次

Knowledge point: Bit operation array

Method 1: Bit operations

analyze:

For counting the number of occurrences of numbers, you can think of a Hash table, but this does not use the feature that each element appears exactly three times. Or the time complexity of using sorting and then performing statistics may be higher than O(n). But if you have no ideas during the interview, you can answer the question first and let the interviewer guide you to continue answering.

There is a simplified version of this question similar to "In the input array, except for one number that appears only once, all other numbers appear twice. Please find the number that only appears once." The result of XORing any number with itself is 0. If you XOR all the numbers in the array, the final result is the number that appears only once.

Consider the binary form of a number. Add the digits at the same position of all numbers in the array.

If the numbers that appear three times are taken out separately, then the sum of any i-th digit of these numbers that appear three times can be divisible by 3. Therefore, if the sum of the i-th digits of all numbers in the array is divisible by 3, then the i-th digit of a number that appears only once must be 0; if the sum of the i-th digits of all numbers in the array is divisible by 3 If the remainder is 1, then the i-th digit of a number that appears only once must be 1.

Count the number of occurrences of 1 in each binary digit of all numbers, and find the remainder of 3. The result is a number that appears only once.

 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function(nums) {
    
    let arr = new Array(32).fill(0);
    for (let i = 0; i<nums.length; i++) {
        for (let j = 0; j<32; j++) {
            
            
            arr[j] += (nums[i] >> (31 - j)) & 1;
        }
    }

    
    let res = 0;
    for (let i = 0; i<32; i++) {
        res = (res << 1) + (arr[i] %3);
    }
    return res;
};

Complexity analysis

  • Time complexity: O(n)

  • Space complexity: O(1)

so

  • The ending is still the same: there will be times when the wind and waves break, and the clouds and sails will sail directly to the sea!

  • The online collection is indeed very good. I have summarized and organized the articles, online preparation guide for interviews and question answering. You can take it away without any thanks. You must learn to stand on the shoulders of others and improve yourself. Click here --> 

     

    at last:

    If you are looking for a job now, you can send a private message to "web" or directly add an assistant to the group to receive the front-end interview brochure, resume optimization and modification, internal recommendations from major manufacturers , and more collections of real interview questions from Alibaba, Byte and major manufacturers , and p8 bosses Communicate together. 

Guess you like

Origin blog.csdn.net/Likestarr/article/details/135228406