我用JS刷LeetCode | Day 10 | Search Insert Position

我用JS刷LeetCode | Day 10 | Search Insert Positionjavascript

搜索插入位置:

说明:现阶段的解题暂未考虑复杂度问题

首发地址:http://www.brandhuang.com/article/1584366828427前端

Question:

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.java

You may assume no duplicates in the array.算法

中文题目:

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。若是目标值不存在于数组中,返回它将会被按顺序插入的位置。数组

你能够假设数组中无重复元素。微信

Example:数据结构

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

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

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

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

我的分析:

  1. 读完题目咱们能够获得的信息:「排序数组」,返回目标值在数组中的索引数组中元素不重复
  2. 咱们只须要 遍历数组,将每一个元素和目标值相比,当数组中元素第一次大于或者等于目标值时,说明目标值在数组中的位置就是该元素如今的位置.
  3. 因而获得答案。

Answer:

var searchInsert = function(nums, target) {
    for (var i = 0; i < nums.length; i++) {
       if (nums[i] >= target) {
           return i
       }
    }
    return nums.length
};

说明

发现最近的题开始须要有一点数据结构的知识了,因此刷题的速度会放慢,须要去补充下数据结构的知识。spa

以前在博客发了两篇,能够看看:code

JavaScript版数据结构与算法——基础篇(一)排序

JavaScript版数据结构与算法——基础篇(二)

其余:

本题更多 JavaScript 解析,点击连接访问对应的答案:https://leetcode.com

若有兴趣扫码或微信搜索「九零后重庆崽儿」,咱们一块儿学前端。

brand.jpg

相关文章
相关标签/搜索