LeetCode-Search Insert Position

来源:互联网 发布:防止wifi蹭网软件 编辑:程序博客网 时间:2024/05/22 23:58
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/39179649
时间:2014-9-10

题目

Search Insert Position

 Total Accepted: 24487 Total Submissions: 69913My Submissions

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


解法

代码
public class Solution {    public int searchInsert(int[] A, int target) {        int lo = -1;        int hi = A.length;        int mid = lo + (hi - lo)/2;        while(lo+1 != hi){            mid = lo + (hi - lo)/2;            if(A[mid] == target)                return mid;            else if(A[mid] > target){                if(mid > 1 && A[mid-1] < target)                    return mid;                else if(mid == 0 )                    return mid;                hi = mid;            }            else{                if( A.length > mid + 1 && A[mid+1] > target)                    return mid+1;                else if(A.length == mid + 1)                    return mid+1;                lo = mid;            }        }        return mid;            }}


结果
Submit TimeStatusRun TimeLanguage13 hours, 28 minutes agoAccepted392 msjava

返回

LeetCode Solution(持续更新,java>c++)
0 0
原创粉丝点击