zoukankan      html  css  js  c++  java
  • [LeetCode] Search Insert Position

    https://leetcode.com/problems/search-insert-position/

    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.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    解法一:

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
             int left = 0, right = nums.size() - 1, middle;
             // 保证可以缩小范围,当只剩下一个数的时候退出循环
             while (left < right) {
                 middle = (left + right) >> 1;
                 if (target == nums[middle]) {
                     return middle;
                 } else if (target > nums[middle]) {
                     left = middle + 1; // 当只有两个数的时候,由于middle会指向左边的数字,为了确保一定可以缩小范围,因此此处令middle+1
                 } else if (target < nums[middle]) {
                     right = middle;
                 }
             }
             
             if (target == nums[left]) {
                 return left;
             } else if (target > nums[left]) {
                 return left + 1;
             } else if (target < nums[left]) {
                 return left;
             }
        }
    }

    解法二:

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int left = 0, right = nums.size() - 1, middle;
            while (left + 1 < right) {
                middle = (left + right) >> 1;
                if (target == nums[middle]) {
                    return middle;
                } else if (target < nums[middle]) {
                    right = middle;
                } else {
                    left = middle;
                }
            }
            
            // 如果退出循环,只剩下两个数
            if (target <= nums[left]) {
                return left;
            } else if (nums[left] < target && target <= nums[right]) {
                return left + 1;
            } else if (target > nums[right]){
                return right + 1;
            }
        }
    };
  • 相关阅读:
    牌库读取的修复
    法术迸发(Spellburst)
    传染孢子的探索
    降低电脑功耗——降低笔记本风扇噪音
    Playfield 类方法的注释
    大陆争霸( 最短路变形)
    POJ 2406 Power String
    括号匹配
    HDU 1003 最大子段和
    6.19noip模拟赛总结
  • 原文地址:https://www.cnblogs.com/jianxinzhou/p/4521957.html
Copyright © 2011-2022 走看看