LeetCode OJ-35-Search Insert Position

来源:互联网 发布:瑞士军刀软件 编辑:程序博客网 时间:2024/06/05 18:48

题目:

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

大意:

给定一个排序数组,和一个指定的值,如果找到这个值,返回这个值位置,如果没有找到,返回这个值在数组中的插入位置。假设数组中没有重复的元素。

思路:

使用二分查找,时间复杂度为O(log(n))。

代码:

public class Solution {    public int searchInsert(int[] nums, int target) {        if(nums == null) {            return -1;        }        int i = 0;        int j = nums.length - 1;        int mid;        while(i <= j) {            mid = (i + j) / 2;            if(nums[mid] == target) {                return mid;            } else if(nums[mid] < target) {                i = mid + 1;            } else {                j = mid - 1;            }        }        return i;    }}
1 0
原创粉丝点击