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

    原题链接:https://leetcode.com/problems/search-insert-position/description/
    这道题目直接上二分查找即可:

    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        public static void main(String[] args) throws InterruptedException {
            Solution s = new Solution();
            /**
             * Example 1:
    
             Input: [1,3,5,6], 5
             Output: 2
             Example 2:
    
             Input: [1,3,5,6], 2
             Output: 1
             Example 3:
    
             Input: [1,3,5,6], 7
             Output: 4
             Example 1:
    
             Input: [1,3,5,6], 0
             Output: 0
    
             */
            System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 5));
            System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 2));
            System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 7));
            System.out.println(s.searchInsert(new int[]{1, 3, 5, 6}, 0));
        }
    
        public int searchInsert(int[] nums, int target) {
            if (nums.length == 0) {
                return 0;
            }
            if (target < nums[0]) {
                return 0;
            }
            if (target > nums[nums.length - 1]) {
                return nums.length;
            }
    
            int start = 0;
            int end = nums.length - 1;
            while (start <= end) {
                int middle = (start + end) / 2;
                if (target > nums[middle]) {
                    start = middle + 1;
                } else if (target < nums[middle]) {
                    end = middle - 1;
                } else {
                    return middle;
                }
            }
    
            return start;
        }
    
    }
    
  • 相关阅读:
    C++中的类模板详细讲述
    函数模板和模板函数
    vs2008 快捷键大全
    #宏定义##
    多工程项目设置
    conemu 配置
    itcast-svn
    itcast-spring-三大框架整合
    Spring通知方法错误
    动态代理
  • 原文地址:https://www.cnblogs.com/optor/p/8572409.html
Copyright © 2011-2022 走看看