Alice has ahandof cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is sizeW, and consists ofWconsecutive cards.
Returntrueif and only if she can.
Example 1:
Input:
hand = [1,2,3,6,2,3,4,7,8], W = 3
Output:
true
Explanation:
Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
Example 2:
Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation:
Alice's hand can't be rearranged into groups of 4.
Note:
1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length
2. Implementation
(1) Bucket Sort
思路: Bucket Sort的思路并不是很懂
class Solution {
public boolean isNStraightHand(int[] hand, int W) {
if (W == 1) return true;
if (hand.length % W != 0) return false;
int n = hand.length;
int H = n / W;
int[][] buckets = new int[W][H];
int[] bucketSize = new int[W];
// each column is a bucket
for (int card : hand) {
// use card % W to find the position of card in the bucket
int indexInBucket = card % W;
int bucketId = bucketSize[indexInBucket]++;
if (bucketId >= H) {
return false;
}
buckets[indexInBucket][bucketId] = card;
}
for (int i = 0; i < W; i++) {
Arrays.sort(buckets[i]);
}
for (int j = 0; j < H; j++) {
for (int i = 1; i < W; i++) {
int pre = buckets[i - 1][j];
int cur = buckets[i][j];
if (pre + 1 != cur && pre - cur != W - 1) return false;
}
}
return true;
}
}