题解 | #将真分数分解为埃及分数#

Redraiment的走法

http://www.nowcoder.com/practice/24e6243b9f0446b081b1d6d32f2aa3aa

代码清晰,好理解:

import java.util.*;

public class Main {
    // 其实就是最长上升子序列
    // 利用二分来查找要插入的位置
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int numCount = in.nextInt();

            int[] nums = new int[numCount];
            for (int i = 0; i < numCount; i++) {
                nums[i] = in.nextInt();
            }

            List<Integer> ascList = new ArrayList<>();
            for (int i = 0; i < numCount; i++) {
                int target = nums[i];
                if (ascList.size() == 0 || target > ascList.get(ascList.size() - 1)) {
                    ascList.add(target);
                } else {
                    int left = 0, right = ascList.size() - 1;
                    int pos = -1;
                    while (left <= right) {
                        int mid = (left + right) / 2;
                        int searchVal = ascList.get(mid);
                        if (target == searchVal) {
                            pos = mid;
                            break;
                        } else if (target > searchVal) {
                            left = mid + 1;
                        } else {
                            // 保存右边界,让右侧更紧密,左侧更稀疏,进而左侧有更多机会寻找更小的数字
                            pos = mid;
                            right = mid - 1;
                        }
                    }
                    ascList.set(pos, target);
                }
            }

            System.out.println(ascList.size());
        }
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 18:14
RT,这周五就是情人节了,前女友给我发了消息,我该不该回?
Yoswell:原则上来说让她滚,但是本着工作很累下班想吃瓜的心态,我觉得你可以回一下
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务