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;
    	}
    }
    
  • 相关阅读:
    POJ 2752 Seek the Name, Seek the Fame
    POJ 2406 Power Strings
    对闭包的理解(closure)
    HDU
    Python字典遍历的几种方法
    面向对象的六大原则
    Android添加代码检查权限
    Android请求网络权限
    android广播接收器BroadcastReceiver
    Android中SQLite下 Cursor的使用。
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4966833.html
Copyright © 2011-2022 走看看