愛麗絲有一手(hand)由整數(shù)數(shù)組給定的牌。
現(xiàn)在她想把牌重新排列成組,使得每個組的大小都是 W,且由 W 張連續(xù)的牌組成。
如果她可以完成分組就返回 true,否則返回 false。
示例 1:
輸入:hand = [1,2,3,6,2,3,4,7,8], W = 3
輸出:true
解釋:愛麗絲的手牌可以被重新排列為 [1,2,3],[2,3,4],[6,7,8]。
示例 2:
輸入:hand = [1,2,3,4,5], W = 4
輸出:false
解釋:愛麗絲的手牌無法被重新排列成幾個大小為 4 的組。
提示:
1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length
public class Shunzi {
/**
* 思路:
* 1.先將數(shù)組排序,然后加到list中
* 2.從list頭部開始取出連續(xù)的W個數(shù)
* 3.如果上一步數(shù)組長度不夠,或者取不出W個連續(xù)的數(shù),返回false
* 4.重復(fù)2操作
* @param hand
* @param W
* @return
*/
public static boolean isNStraightHand(int[] hand, int W) {
Arrays.sort(hand);
int len = hand.length;
if(len % W != 0){
return false;
}
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < len; i++){
list.add(hand[i]);
}
while(list.size() > 0){
Integer curVal = list.get(0);
for(int i = 0; i < W; i++){
if(list.size() == 0)
return false;
if(! list.remove(curVal) )
return false;
curVal++;
}
}
return true;
}
public static void main(String[] args) {
int a[] = new int[]{1,2,3,4,5};
System.out.println(isNStraightHand(a,4));
}
}