zoukankan      html  css  js  c++  java
  • LeetCode OJ 35. Search Insert Position

    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

    【题目分析】

    给定一个已排序的数组,数组中没有重复的数字。给定一个数字找到该数子出现的位置,如果数组中不存在该数字,则返回如果插入该数字应该插入的位置。

    【思路】

    涉及到已排序的数组,我们一般都会采用二分查找算法。如果目标数字存在,则直接返回结果即可。若不存在呢?

    研究一下二分查找,left和right相等时,如果此时的值和目标值相同则left就是应该返回的结果,否则的话我们比较一下目标值和下标left对应的值的大小。如果目标值较大,则返回left+1,否则返回left。

    【java代码】

     1 public class Solution {
     2     public int searchInsert(int[] nums, int target) {
     3         if(nums.length == 0 || nums == null) return 0;
     4         
     5         int left = 0;
     6         int right = nums.length - 1;
     7         
     8         while(left <= right){
     9             if(left == right){
    10                 if(nums[left] == target) return left;
    11                 else break;
    12             }
    13             int mid = (right - left)/2 + left;
    14             if(nums[mid] > target) right = mid - 1;
    15             else if(nums[mid] < target) left = mid + 1;
    16             else return mid;
    17         }
    18         if(nums[left] < target) return left+1;
    19         else return left;
    20     }
    21 }
  • 相关阅读:
    测试开发之利器论战
    测试开发的战略战术
    Python日志Logging
    Android自动测试中的monkey工具使用方法
    ADB命令讲解
    学习要深入
    测试开发发展感触
    Web Service测试工具小汇
    python接口测试浅谈
    手机上app测试总结(转)
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5521959.html
Copyright © 2011-2022 走看看