zoukankan      html  css  js  c++  java
  • 35. Search Insert Position

        /*
         * 35. Search Insert Position 
         * 2016-5-2 by Mingyang 这道题目偏简单
         * 这只是常规的解法,后面我们来logn的解法
         */
        public int searchInsert(int[] nums, int target) {
            if (nums == null || nums.length == 0)
                return 0;
            if (target < nums[0])
                return 0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] >= target)
                    return i;
            }
            return nums.length;
        }
        /*
         * 然后自己给出了一个Binary Search的解法,
         * 但是思路非常混乱 列下来以儆效尤
         */
        public int searchInsert1(int[] nums, int target) {
            int len = nums.length;
            if (nums == null || len == 0)
                return 0;
            if (target < nums[0])
                return 0;
            if (target > nums[len - 1])
                return len;
            int start = 0;
            int end = len - 1;
            while (start < end) {
                int mid = (start + end) / 2;
                if (nums[mid] == target) {
                    return mid;
                } else if (nums[mid] < target) {
                    start = mid;
                    if (start + 1 == end)
                        return end;
                } else {
                    end = mid;
    
                }
            }
            return start;
        }
        // 史上最标准答案,最简洁的一种BS的方法,只需要了解为什么后面返回low就好了
        public int searchInsert2(int[] nums, int target) {
            int low = 0, high = nums.length - 1;
            while (low <= high) {
                int mid = (low + high) / 2;
                if (nums[mid] == target)
                    return mid;
                else if (nums[mid] > target)
                    high = mid - 1;
                else
                    low = mid + 1;
            }
            return low;
        }
  • 相关阅读:
    cross-domain
    【转】React、Vue访问NotFound
    Flutter环境配置
    antd遇见的坑
    npm源设置
    React中的生命周期函数
    【备忘】javascript原型、Function、eval、闭包、json处理、类、arguments不定
    ADB获取手机信息
    selenium操作
    操作execl
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5457226.html
Copyright © 2011-2022 走看看