Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

35. Search Insert Position #206

Open
Tcdian opened this issue Jun 10, 2020 · 1 comment
Open

35. Search Insert Position #206

Tcdian opened this issue Jun 10, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 10, 2020

35. Search Insert Position

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

你可以假设数组中无重复元素。

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
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 10, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    const len = nums.length;
    if (len === 0 || nums[len - 1] < target) {
        return len;
    }
    let left = 0;
    let right = nums.length - 1;
    while (left < right) {
        const mid = (left + right) >> 1;
        if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
};
  • TypeScript Solution
function searchInsert(nums: number[], target: number): number {
    const len = nums.length;
    if (len === 0 || nums[len - 1] < target) {
        return len;
    }
    let left = 0;
    let right = nums.length - 1;
    while (left < right) {
        const mid = (left + right) >> 1;
        if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}

@Tcdian Tcdian added the Classic label Jun 13, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant