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
  • 相关阅读:
    列表、元组、字典等相关命令
    字符串相关命令
    Python简介
    二进制的趣事
    Shell脚本基础
    Linux基本服务
    一次性计划任务at与周期性计划任务crontab
    Linux权限管理
    python-文件操作
    python-初识python
  • 原文地址:https://www.cnblogs.com/immjc/p/7234891.html
Copyright © 2011-2022 走看看