zoukankan      html  css  js  c++  java
  • 35. Search Insert Position(LeetCode)

    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

     1 class Solution {
     2 public:
     3     int searchInsert(vector<int>& nums, int target) {
     4             int  local = -1;
     5         vector<int>::iterator ite;
     6         ite=find(nums.begin(), nums.end(), target);
     7         if (ite == nums.end())
     8         {
     9             nums.push_back(target);
    10             sort(nums.begin(), nums.end());
    11             for (int i = 0; i < nums.size(); i++)
    12             {
    13                 if (nums[i] == target)
    14                     local = i;
    15             }
    16         }
    17         else
    18         {
    19             for (int i = 0; i < nums.size(); i++)
    20             {
    21                 if (nums[i] == target)
    22                     local = i;
    23             }
    24         }
    25         return local;
    26     }
    27 };

    别人的代码,很聪明

     1 class Solution {
     2 public:
     3     int searchInsert(vector<int>& nums, int target) {
     4          for (int i = 0; i < nums.size(); i++) {
     5             if (target <= nums[i])
     6                 return i;
     7         }
     8         return nums.size();
     9     }
    10 };
  • 相关阅读:
    Go 打印出结构化结构体
    GOPROXY设置
    python判断链表是否有环
    单链表python和go的代码
    mongo索引
    python修改srt字幕的时间轴
    python各个版本的排序
    mac使用python识别图形验证码
    selenium运行js代码笔记
    布隆过滤器
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6894562.html
Copyright © 2011-2022 走看看