zoukankan      html  css  js  c++  java
  • 力扣(LeetCode)试题35-搜索插入位置 C++代码

    这个比较简单,不写注释了(逐个比较数组元素与target值大小,若小于,则下一个,直到不小于,返回此时的索引值即可,下一个值是大于它还是等于他,target都要插入这里)

    注意要跳出循环。

     1 #include <iostream>
     2 #include <vector>
     3 
     4 using namespace std;
     5 
     6 class Solution {
     7 public:
     8     int searchInsert(vector<int>& nums, int target) 
     9     {
    10         int result;
    11         for (int i = 0; i < nums.size(); i++)
    12         {
    13             if (nums[i] < target) continue;
    14             else
    15             {
    16                 result = i;
    17                 break;
    18             }
    19         }
    20         return result;
    21     }
    22 };
    23 
    24 int main()
    25 {
    26     vector<int> nums = { 1, 3, 5, 6 };
    27     int target = 2;
    28     Solution sol;
    29     int result;
    30     result = sol.searchInsert(nums, target);
    31     cout << result << endl;
    32     int p;
    33     cin >> p;
    34 
    35     return 0;
    36 }

  • 相关阅读:
    纯快排
    Quick Sort(快速排序)
    归并排序 ALDS1_5_B:Merge Sort
    单调栈(POJ2559)
    Sequence
    Codeforces Round #503
    度度熊学队列
    Always Online hdu 6350
    Hills And Valleys
    Problem G. Depth-First Search
  • 原文地址:https://www.cnblogs.com/pgzhanglin/p/13254551.html
Copyright © 2011-2022 走看看