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;
    	}
    }
    
  • 相关阅读:
    ADO.NET调用存储过程
    存储过程
    web Servise(服务)
    ADO.NET连接池
    ADO.NET
    常用语法2
    常用语法
    修改pip源为国内网站
    模块
    random模块
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4966833.html
Copyright © 2011-2022 走看看