Search Insert Position

来源:互联网 发布:程序员 团队贡献 编辑:程序博客网 时间:2024/06/05 08:36

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.


主要内容:返回在给定已正向排序的数组中返回符合条件的数的位置序号,如果没有找到就返回假设要插入该数组的位置序号


解题思想:在vector中遍历,如果找到就返回,如果没找到就再遍历如果能找到>=target的数就安插在前一位,反之则是最后一位


参考C++代码:

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int s = nums.size();        int n = 0;        int c = 0;        for(int i = 0; i < s; i++) {            if(nums[i] == target) {                return i;            } else {                n++;            }        }        if(n == s) {            for (int i = 0; i < s; i++) {                if(nums[i] >= target) {                    return i;                } else {                    c++;                }            }            if(c == s) {                return s;            }        }    }};


原创粉丝点击