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

    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

    解题思路:

    使用二分法搜索,当出现相等的情况就返回该位置的值;否则结果是right < left;这表明在上一次循环中出现两种情况:1、mid位置的值大于target,则最后一次循环后right = mid - 1,所以插入的位置肯定为right + 1的位置;2、mid位置的值小于target,则最后一次循环后left = mid + 1,所以插入的位置肯定为right + 1。综上,代码如下所示:

    代码如下:

    public class Solution {
        public static int searchInsert(int[] nums, int target) {
    		int left, right, mid;
    		left = 0;
    		right = nums.length - 1;
    
    		while (left <= right) {
    			mid = (left + right) / 2;
    			if (nums[left] == target)
    				return left;
    			if (nums[right] == target)
    				return right;
    			if (nums[mid] == target)
    				return mid;
    
    			if (nums[mid] > target)
    				right = mid - 1;
    			else if (nums[mid] < target)
    				left = mid + 1;
    		}
    		return right + 1;
    	}
    }
    
  • 相关阅读:
    Nth Highest Salary
    第二高的薪水
    组合两个表
    牛客(66)机器人的运动范围
    牛客(65)矩阵中的路径
    牛客(64)滑动窗口的最大值
    牛客(63)数据流中的中位数
    牛客(62)二叉搜索树的第k个结点
    牛客(61)序列化二叉树
    mybits(2)增删改查
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4966833.html
Copyright © 2011-2022 走看看