中级农民
- 积分
- 109
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-3-16
- 最后登录
- 1970-1-1
|
Java代码:
- // 千万不要抄啊
- static class DataEntry{
- int index;
- int floorVal;
- double diff;
- public DataEntry(int index, int floorVal, double differenceFromFloor){
- this.index = index;
- this.floorVal = floorVal;
- this.diff = differenceFromFloor;
- }
- }
- public static List<Integer> Solution5(List<Double> prices, int target){
- DataEntry[] entries = new DataEntry[prices.size()];
- int floorSum = 0, xFloor;
- double x;
- for(int i=0; i<prices.size(); i++){
- x = prices.get(i);
- xFloor = (int)x;
- floorSum += xFloor;
- DataEntry newDataEntry = new DataEntry(i, xFloor, x - xFloor);
- entries[i] = newDataEntry;
- }
- int totalDiff = target - floorSum;
- Arrays.sort(entries, (a, b) -> a.diff >= b.diff ? -1 : 1); // sort entries according to difference
- int idx = 0;
- while(idx < totalDiff){
- entries[idx] = new DataEntry(entries[idx].index, entries[idx].floorVal+1, entries[idx].diff); // add 1 to the first diff entries
- idx++;
- }
- Arrays.sort(entries, (a, b) -> a.index < b.index ? -1 : 1); // sort entries according to original idx
- List<Integer> result = new ArrayList();
- for(int i=0; i<prices.size(); i++){
- result.add(entries[i].floorVal);
- }
- return result;
- }
复制代码
测试:
- public static void main(String[] args) {
- double[] arr = { 1.2, 3.7, 2.3, 4.8, 5.0, 6.7}; // fine
- List<Double> prices = Arrays.stream(arr).boxed().collect(Collectors.toList());
- int target = 24;
- List<Integer> res = Solution5(prices, target);
- for(int i: res)
- System.out.print(i + " ");
- }
复制代码
补充内容 (2018-11-16 15:57):
选择语言是Java 8 |
|