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

【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 {(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 {(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;}}评测结果

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

直接算法

二分查找算法

特别说明欢迎转载,转载请注明出处【】

你可以这样理解 impossible(不可能)–I'm possible (我是可能的)。

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

相关文章:

你感兴趣的文章:

标签云: