Leet Code OJ 338. Counting Bits [Difficulty: Medium]

题目:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example:

For num = 5 you should return [0,1,1,2,1,2].

Follow up:

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?

Space complexity should be O(n).

Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Hint:

You should make use of what you have produced already.

翻译:

给定一个非负整数num,对于每一个0<=i<=num的整数i。计算i的二进制表示中1的个数,返回这些个数作为一个数组。

比如。输入num = 5 你应该返回 [0,1,1,2,1,2].

分析:

依照常规思路,非常容易得出“Java代码2”的方案。可是这个方法的时间复杂度是O(nlogn)。

通过对数组的前64个元素进行分析(num=63),我们发现数组呈现一定的规律,不断重复。例如以下图所看到的:

0
1
1 2
1 2 2 3
1 2 2 3 2 3 3 4
1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5
1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6 

由此我们发现0112是一个基础元素。不断循环重复。能够推论:假设已知第一个元素是result[0],那么第二第三个元素为result[0]+1,第四个元素为result[0]+2,由此获得前4个元素result[0]~result[3]。以这4个元素为基础。我们能够得到

result[4]=result[0]+1,result[5]=result[1]+1…。

result[8]=result[0]+1,result[9]=result[1]+1… ,

result[12]=result[0]+2,result[13]=result[1]+2…;

以此类推能够获得所有的数组。

Java版代码1:

public class Solution {
    public int[] countBits(int num) {
        int[] result = new int[num + 1];
        int range = 1;
        result[0] = 0;
        boolean stop = false;
        while (!stop) {
            stop = fillNum(result, range);
            range *= 4;
        }
        return result;
    }

    public boolean fillNum(int[] nums, int range) {
        for (int i = 0; i < range; i++) {
            if (range + i < nums.length) {
                nums[range + i] = nums[i] + 1;
            } else {
                return true;
            }
            if (2 * range + i < nums.length) {
                nums[2 * range + i] = nums[i] + 1;
            }
            if (3 * range + i < nums.length) {
                nums[3 * range + i] = nums[i] + 2;
            }
        }
        return false;
    }
}

Java版代码2:

public class Solution {
    public int[] countBits(int num) {
        int[] result=new int[num+1];
        result[0]=0;
        for(int i=1;i<=num;i++){
            result[i]=getCount(i);
        }
        return result;
    }
    public int getCount(int num){
        int count=0;
        while(num!=0){
            if((num&1)==1){
                count++;
            }
            num/=2;
        }
        return count;
    }
}
时间: 2024-10-15 08:56:38

Leet Code OJ 338. Counting Bits [Difficulty: Medium]的相关文章

Leet Code OJ 338. Counting Bits [Difficulty: Easy]

题目: Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is v

Leet Code OJ 91. Decode Ways [Difficulty: Medium]

题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given enc

Leet Code OJ 189. Rotate Array [Difficulty: Easy]

题目: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve thi

Leet Code OJ 66. Plus One [Difficulty: Easy]

题目: Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. 翻译: 给定一个非负数,它是有数字的数组组成,把这个非负数+1. 这个非负数的存储方式,是把最高有效位数字放到列表的前面. 分析: 首先考虑的是

Leet Code OJ 1. Two Sum [Difficulty: Easy]

题目: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1]

Leet Code OJ 27. Remove Element [Difficulty: Easy]

题目: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 翻译: 给定一个数组和一个值,在原地移除所有的这个值的实例,并且返回新的数组长度. 元素的顺序可以被改变.

Leet Code OJ 223. Rectangle Area [Difficulty: Easy]

题目: Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. Assume that the total area is never beyond the maximum possible value of int

Leet Code OJ 344. Reverse String [Difficulty: Easy]

题目: Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". 翻译: 写一个函数,使用字符串作为输入,返回它反转后的结果. 例如,输入"hello",返回"olleh". 分析: 转为字符数组后,将第一个字符和最后一个字符对调,第二个字符

Leet Code OJ 28. Implement strStr() [Difficulty: Easy]

题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 翻译: 实现一个方法strStr().返回字符串needle第一次在字符串haystack出现的下标,如果needle不是haystack的一部分,就返回-1. 分析: 在文本中查找某个模式出现的位置的算法,称为字符串匹配算法.常用的方法有