Leetcode One Question of the Day 2020.11.06 Question 1356: Sort according to the number of 1 under the digital binary

1356. Sort according to the number of 1 under digital binary

Title description

Insert picture description here

Example

Insert picture description here
Insert picture description here

Ideas, algorithms and code implementation

		先将数组arr中的元素用内置函数bin()转换成二进制字符串,再利用字符串的常用方法count()计算二进制里'1'的个数。使用哈希表(字典),建立<二进制1的次数,[数字1,数字2,...]>的映射关系。我一开始想的是,用每个数字当key,二进制1的次数当value,排序之后,考虑当二进制1的数目相等的情况下,按数字大小排序就复杂了。而<二进制1的次数,[数字1,数字2,...]>这种方法,更简便直观。注意:字典的key只能是不可变类型,所以如果[数字1,数字2,...]当key的话是不行的。
		接下来,用sorted()函数先按二进制1的数目排序,得到一个顺序表keys(),按照这个顺序表,根据字典d的key,对value数组里的数字按大小进行排序,最后依次加到结果数组中。

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_51210480/article/details/109545789