【LeetCode】Search Insert Position 解题报告

来源:互联网 发布:ubuntu注销用户命令 编辑:程序博客网 时间:2024/05/29 02:58

【LeetCode】Search Insert Position 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/search-insert-position/#/description

题目描述:

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

Ways

我用了很愚蠢的方法,分两种情况进行遍历,算法复杂度是O(n).

public class Solution {    public int searchInsert(int[] nums, int target) {        int len = nums.length;        int ans = 0;        for(int i = 0; i < len; i++){            if(nums[i] == target){                ans = i;                break;            }else if((nums[i] < target && i < len - 1 && nums[i + 1] > target)                    || (nums[i] < target && i == len - 1)){                ans = i + 1;                break;            }        }        return ans;    }}

但是,这个是有序的,可以用二分查找的方法。注意,如果查找到结果的要返回mid,没查找到的话返回的是left,因为这个时候left和right已经交叉了,left是比较靠右的位置,也就是应该插入的位置。

public class Solution {    public int searchInsert(int[] nums, int target) {        int left = 0;        int right = nums.length - 1;        int mid = 0;        while(left <= right){            mid = (left + right) / 2;            if(nums[mid] == target){                return mid;            }else if(nums[mid] > target){                right--;            }else{                left++;            }        }        return left;    }}

Date

2017 年 4 月 25 日

0 0
原创粉丝点击