zoukankan      html  css  js  c++  java
  • 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.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    链接:https://leetcode.com/problems/search-insert-position/

    2/11/2017, Java

    这道题主要是通过各种例子来想,下标的想法跟之前一样,一定要想清楚这个下标到底是用来做什么的,避免一会儿返回low, 一会儿发现要返回low + 1这种,不然其实是自己对算法也不了解,就是蒙的。

    这道题思路主要是如果范围缩小到一个值,怎么判断,所以循环条件不是low <= high,而是low < high,我们把low = high这个条单独拿出来判断。low > high这种是超了边界,就很容易解决。

     1 public class Solution {
     2     public int searchInsert(int[] nums, int target) {
     3         if (nums == null) return 0;
     4         
     5         int low = 0;
     6         int high = nums.length - 1;
     7         int mid;
     8         
     9         while (low < high) {
    10             mid = low + (high - low) / 2;
    11             if (nums[mid] == target) return mid;
    12             else if (nums[mid] > target) {
    13                 high = mid - 1;
    14             } else {
    15                 low = mid + 1;
    16             }
    17         }
    18         if (low == high) {
    19             if (nums[low] == target) return low;
    20             else if (nums[low] > target) return low;
    21             else if (nums[low] < target) return low + 1;
    22         } else {
    23             return low;
    24         }
    25         return 0;
    26     }
    27 }
  • 相关阅读:
    leetcode之Search in Rotated Sorted Array
    leetcode之Search Insert Position2
    leetcode之Search Insert Position
    二分查找之Search for a Range
    leetcode之Two Sum
    leetcode之Spiral Matrix II
    leetcode之Spiral Matrix
    杨辉三角
    周计划1[7.22~7.28]
    英美音的比较
  • 原文地址:https://www.cnblogs.com/panini/p/6390422.html
Copyright © 2011-2022 走看看