zoukankan      html  css  js  c++  java
  • [LeetCode] 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) {
            nums.push_back(target);
            sort(nums.begin(), nums.end());
            int res = 0;
            for (int i = 0; i != nums.size(); i++) {
                if (nums[i] == target) {
                    res = i;
                    break;
                }
            }
            return res;
        }
    };
    // 6 ms

     使用二分搜索也可。

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int left = 0, right = nums.size() - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] < target)
                    left = mid + 1;
                else
                    right = mid - 1;
            }
            return left;
        }
    };
    // 6 ms
  • 相关阅读:
    wpf Behavior
    wpf Trigger
    语法糖
    Lambda 表达式
    wpf 3D动画
    IEnumerable接口学习
    Delegates, Events, and Anonymous Methods 委托、事件与匿名方法
    wpf 平滑效果随记
    软件工程第一篇博客
    记考研高数第一课
  • 原文地址:https://www.cnblogs.com/immjc/p/7234891.html
Copyright © 2011-2022 走看看