码迷,mamicode.com
首页 > 编程语言 > 详细

【LeetCode-面试算法经典-Java实现】【035-Search Insert Position(搜索插入位置)】

时间:2015-07-27 08:16:01      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:数组   搜索   算法   面试   java   

【035-Search Insert Position(搜索插入位置)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

  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) {

        if (A == null) {
            return -1;
        }

        int i;
        for (i = 0; i < A.length; i++) {
            if (A[i] >= target) {
                return i;
            }
        }

        return i;
    }
}

算法实现类(二分查找)

public class Solution {
    public int searchInsert(int[] A, int target) {

        int mid;
        int lo = 0;
        int hi = A.length - 1;

        while (lo <= hi) {
            mid = lo + (hi - lo)/ 2;

            if (A[mid] == target) {
                return mid;
            } else if (A[mid] < target){
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        return lo;
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

直接算法
技术分享

二分查找算法
技术分享

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47079367

版权声明:本文为博主原创文章,未经博主允许不得转载。

【LeetCode-面试算法经典-Java实现】【035-Search Insert Position(搜索插入位置)】

标签:数组   搜索   算法   面试   java   

原文地址:http://blog.csdn.net/derrantcm/article/details/47079367

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