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. 搜索插入位置 #31

Open
zpc7 opened this issue Aug 10, 2022 · 0 comments
Open

35. 搜索插入位置 #31

zpc7 opened this issue Aug 10, 2022 · 0 comments
Labels
简单 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 10, 2022

35. 搜索插入位置

参考题解:

function searchInsert(nums: number[], target: number): number {
    // 二分法, 建议画图理解
    let left = 0;
    let right = nums.length - 1;

    while (left <= right) {
        // 中间节点, 这边使用向下取整
        let mid = Math.floor((right + left) / 2);

        // 相等, 找到目标值
        if (nums[mid] === target) {
            return mid;
        } else if (nums[mid] < target) { // 目标值比中间值大, 需要左边的位置右移
            left = mid + 1; // left 就是将要返回的值 (将会被按顺序插入的位置)(下一次二分比较的左边位置)
        } else if (nums[mid] > target) { // 否则右边的位置左移
            right = mid - 1;
        }
    }

    return left;
}
@zpc7 zpc7 added 简单 LeetCode 难度定级 JS and removed JS labels Aug 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant