35. Search Insert Position ( JavaScript )

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.
数组里的值没有重复的。

  • Example 1:

    • Input: [1,3,5,6], 5
      Output: 2
  • Example 2:

    • Input: [1,3,5,6], 2
      Output: 1
  • Example 3:

    • Input: [1,3,5,6], 7
      Output: 4
  • Example 4:

    • Input: [1,3,5,6], 0
      Output: 0

解析:

这个常见解法就是二分法了,数组分两半,看要左边这半还是右边这半,再把这半边分两半,只是在判断要左半还是右半的时候,把下标值保存,如果是左边,保存左边下标值最大的那个,右边保存最小的那个,当最后发现右边保存的这个值要比左边这个值大了或者等于左边了,就可以返回了。

(The following English translation may not be right -.-)

analyze:

Solve this problem with dichotomy : divide the array into two halves from the middle, if the target should be in the left part, then remain the left part and store the 「index」largest one of the left part, if the target should be in the right part, we should store the 「index」smallest one of the right part, then continue divide the remaining half.

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    if (!nums || !nums.length) return 0;
    
    var index = -1;
    var max = nums.length;
    var min = 0;
    while(index === -1) {
        // console.log('max, min: ', max, " ", min);
        var current = Math.floor((max + min) / 2);
        // console.log("current: ", current);
        if (nums[current] === target) {
            // console.log('index = ', current);
            index = current;
        } else if (nums[current] < target) {
            // console.log(nums[current]);
            min = current + 1;
        } else {
            // console.log('h', nums[current]);
            max = current;
        }
        if (max <= min) {
            // console.log('ind: ', min);
            index = min;
        }
    }
    return index;
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,279评论 0 38
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,979评论 0 13
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,822评论 19 139
  • 在这个大大的世界,每一个小小的我们一定都有过许多或渺小或宏大或现实或奇幻的梦想。而无论是少年,青年还是中年甚至是老...
    青色花蕾阅读 370评论 4 15
  • 今年(2013年)的诺贝尔文学奖给了加拿大女作家爱丽丝门罗,又一个在获奖之前我们对其了解不多的作家。我不喜欢跟风,...
    忘川卡隆阅读 1,724评论 0 5

友情链接更多精彩内容