Skip to content

Commit

Permalink
Merge pull request algorithm004-05#1105 from SimonChu80/master
Browse files Browse the repository at this point in the history
635 -Week 7
  • Loading branch information
melody-li authored Dec 4, 2019
2 parents cae5bee + 98793fe commit 138858a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Week 7/id_635/NumberOf1bits.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.simon.leetcode.w7.lcn191;

public class NumberOf1bits {
public int hammingWeight(int n) {
int ret = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) {
ret++;
}
mask <<= 1;
}
return ret;
}
}
28 changes: 28 additions & 0 deletions Week 7/id_635/RelativeSortArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.simon.leetcode.w7.lcn1122;

public class RelativeSortArray {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
//由于arr1的可能取值为0-1000,共1001个取值,不算一个很大的取值范围,所以可以利用桶式排序
int[] bucket = new int[1001];
//计数每个桶有多少个数,也就是每个值在数组中有几个
for (int num : arr1) {
bucket[num]++;
}
//由于重新排序不会改变数组的长度,所以可以利用原数组,可以节省空间复杂度
int i = 0;
//由于排序是按照相对顺序进行排序,所以,首先根据arr2中的桶的顺序,依次从对应的桶中取数到arr1中
//并注意,每拿出一个数,需要将对桶中的数的个数进行-1操作
for (int num : arr2) {
while (bucket[num]-- > 0) {
arr1[i++] = num;
}
}
//未在arr2中的桶中的数,按照桶号升序进行输出,所以进行二次遍历
for (int j = 0; j < 1001; ++j) {
while (bucket[j]-- > 0) {
arr1[i++] = j;
}
}
return arr1;
}
}

0 comments on commit 138858a

Please sign in to comment.