Leetcode-35 Search Insert Position

来源:互联网 发布:世界十大灾难片 知乎 编辑:程序博客网 时间:2024/06/03 13:12

问题描述

地址:https://leetcode.com/problems/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
翻译:给出排好序的数组和一个目标值(target),如果在数组中有这个target,则返回target的位置,如果数组中没有这个target,返回target应该在数组中的位置。
例如:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

问题解析

由于给出的数组是已经排序好的。所以这个问题可以归结为数组的查找问题,常用我们可以使用二分查找来完成。根据二分查找的一般步骤
(1)定义三个变量i,j,k,其中i指向数组的开始位置,j指向数组的结尾位置,k指向数组的中间位置。
这里写图片描述

(2)如果target>array[k],说明target必须在array[k]后面,这时候需要将i挪动到第k+1位置。
这里写图片描述

(3)如果target< array[k],说明target必须在array[k]前面,这时候将j挪动到第k-1位置。

这里写图片描述

解析代码

public class SearchInsertPosition {    public static void main(String[] args) {        //int[] array1 = {1,3,5,6};//5-2        int[] array1 = {1,2,4,5,6};//5-2        int[] array2 = {1,3,5,6};//2-1        int[] array3 = {1,3,5,6};//7-4        int[] array4 = {1,3,5,6};//0 -0        System.out.println(searchInsert(array1, 3));    }    public static int searchInsert(int[] nums, int target) {        int min = 0;        int max = nums.length -1;        while(min <= max){            int middle = (min + max)/2;            if(nums[middle] == target){                return middle;            }            if(nums[middle] < target){                min = middle + 1;                continue;            }            if(nums[middle] > target){                max = middle - 1;                continue;            }        }       return min;    }}
1 0
原创粉丝点击