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

      Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

      You may assume no duplicates in the array.

    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


    很简单的一个题目,找有序数列里的目标数的下标,找不到就返回可以插入的下标。既然已经排好序,直接用二分法查找即可,一次提交就A掉。上代码。
    public static int searchInsert(int[] nums, int target) {
            if (nums.length == 0||target<nums[0])
                return 0;
            if(target>nums[nums.length-1])return nums.length;
            
            int low, high;
            low = 0;
            high = nums.length - 1;
            while (nums[(low + high) / 2] != target) {
                if (low<high) {
                    if (nums[(low + high) / 2] > target) {
                        
                        high = (low + high) / 2;
                    } else if (nums[(low + high) / 2] < target) {
                        if(low==(low + high) / 2)return (low + high) / 2+1;
                        low = (low + high) / 2;
                    } else {
                        return (low + high) / 2;
                    }
                }
            }
    
            return (low + high) / 2;
        }
  • 相关阅读:
    JSTL笔记(胖先生版)
    EL表达式(胖先生版)
    包装类-Character
    String定义与方法
    冒泡排序(大熊版)
    tomcat Manger App
    第一天
    剑指offer:面试题5、从尾到头打印链表
    剑指offer:面试题4、替换空格
    剑指offer:面试题3、二维数组中的查找
  • 原文地址:https://www.cnblogs.com/GoForMyDream/p/8601452.html
Copyright © 2011-2022 走看看