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;
    	}
    }
    
  • 相关阅读:
    mybatis下使用log4j打印sql语句和执行结果
    chrome不支持embed标签解决方案
    在java中String类为什么要设计成final
    代理模式
    注解(二)模拟实体到数据库表字段的映射
    注解(一)
    python-redistest
    Agens层次聚类
    KNN近邻算法
    K-means聚类算法
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4966833.html
Copyright © 2011-2022 走看看