Search Insert Position

    xiaoxiao2021-03-25  115

    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

    #include<iostream>

    #include<vector> using namespace std; int searchInsert(vector<int>& nums, int target) { int a = nums.size() - 1; int num = a+1; for(int n = 0; n <= a; n++){ if(target <= nums[n]){ num = n; break; } } return num; } int main() { int n; vector<int> q; for(int a = 0; a < 5; a++) { cin >> n; q.push_back(n); } int m; cin >> m; int a = searchInsert(q,m); cout << a; return 0; } 
    转载请注明原文地址: https://ju.6miu.com/read-18591.html

    最新回复(0)