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;
        }
  • 相关阅读:
    洛谷P2751 工序安排Job Processing
    UVA 1613 K度图染色
    线段树+扫描线
    分组背包
    洛谷P5506 封锁
    洛谷P2574 XOR的艺术
    List.Sort
    Dict.Count
    Convert.ToString(null) => null
    Convert 输入字符串的格式不正确
  • 原文地址:https://www.cnblogs.com/GoForMyDream/p/8601452.html
Copyright © 2011-2022 走看看