[LeetCode]35. Search Insert Position 解题报告(C++)

[LeetCode]35. Search Insert Position 解题报告(C++)

题目描述

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.

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

题目大意

  • 给定一个已经排序的数组和给定的值value.
  • 返回这个值的在数组中的坐标.(如果找得到的话.)
  • 否则返回它应该插入的坐标索引.

解题思路

方法1:

  • 二分法

代码实现:


class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        int i = 0, j = n;
        while (i < j) {
            int mid = i + (j - i) / 2;
            int t = nums[mid];
            if (t== target) {
                return mid;
            }
            else if(t<target){
                i = mid + 1;
            }
            else {
                j = mid;
            }
        }
        return i;
    }
};

猜你喜欢

转载自blog.csdn.net/qjh5606/article/details/81411460