Leetcode-35. Search Insert Position

来源:互联网 发布:淘宝详情页的图片大小 编辑:程序博客网 时间:2024/05/29 06:46

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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

这个题比起34更简单一点,首先把一些特殊情况排除了,然后判断一下二分查找有没有找到就行了。Your runtime beats 40.18% of java submissions

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







0 0
原创粉丝点击