题目地址:
https://www.lintcode.com/problem/cut-the-sticks/description
给定若干木棍,长度以数组 A A A表示。每次都将每个木棍切掉当前最短的那根木棍的长度,如果某些木棍长度就是最短的,则丢弃之。问每次被切的木棍的个数,以数组形式返回。
先排序,然后用一个变量记录总切割长度,每次切割的时候记录切的木棍数量,切割完毕之后,用二分求出下一次要切的最短的木棍的下标。代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
/**
* @param sticks: the length of each stick
* @return: return a Integer array
*/
public int[] CutTheSticks(int[] sticks) {
// write your code here
Arrays.sort(sticks);
List<Integer> list = new ArrayList<>();
int idx = 0, len = 0;
while (idx < sticks.length) {
list.add(sticks.length - idx);
len = sticks[idx];
int l = idx + 1, r = sticks.length - 1;
while (l < r) {
int m = l + (r - l >> 1);
if (sticks[m] > len) {
r = m;
} else {
l = m + 1;
}
}
if (l >= sticks.length || sticks[l] <= len) {
break;
}
idx = l;
}
int[] res = new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
return res;
}
}
时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( n ) O(n) O(n)。