码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 16 - Search Insert Position; Array; Binary Search; Iteration&Recursion;---Iteration再补上

时间:2016-01-17 06:29:40      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

Recursion:

代码:

public class Solution {
    public int searchInsert(int[] nums, int target) {
        int len = nums.length;
        if(len == 0) return 0;
        return findPosition(nums, 0, len-1, target);
    }
    
    public int findPosition(int[] nums, int start, int end, int target){
        if(target > nums[end]) return end+1;
        if(target < nums[start]) return start;
        int mid = (start + end)/2;
        int num_mid = nums[mid];
        if(target == num_mid) return mid;
        if(target > num_mid) return findPosition(nums, mid+1, end, target);
        else return findPosition(nums, start, mid-1, target);
    }
}

  Iteration的之后再补上

Jan 16 - Search Insert Position; Array; Binary Search; Iteration&Recursion;---Iteration再补上

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5136740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!