1.leetCode第28题 实现 strStr
需求:
https://leetcode-cn.com/probl...算法
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。若是不存在,则返回 -1
示例 1: 输入:haystack = "hello", needle = "ll" 输出:2 示例 2: 输入:haystack = "aaaaa", needle = "bba" 输出:-1 示例 3: 输入:haystack = "", needle = "" 输出:0
function print(haystack, needle) { return haystack.indexOf(needle) };
function print(haystack, needle) { let reg = new RegExp(needle, "g"); let matchResult = reg.exec(haystack); return matchResult ? matchResult["index"] : -1; }
https://leetcode-cn.com/probl...segmentfault
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。若是目标值不存在于数组中,返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。
示例 1: 输入: nums = [1,3,5,6], target = 5 输出: 2 示例 2: 输入: nums = [1,3,5,6], target = 2 输出: 1 示例 3: 输入: nums = [1,3,5,6], target = 7 输出: 4 示例 4: 输入: nums = [1,3,5,6], target = 0 输出: 0 示例 5: 输入: nums = [1], target = 0 输出: 0
function print(nums, target) { let index = nums.indexOf(target); if (index > -1) return index; for (let i = nums.length; i >= 0; i--) { if (nums[i] < target) { nums.splice(i+1, 0, target); index=i+1 break; } if(i==0){ index=0 nums.unshift(target) } } return index }