forked from algorithm004-05/algorithm004-05
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request algorithm004-05#1105 from SimonChu80/master
635 -Week 7
- Loading branch information
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |