【LeetCode】Search Insert Position

版权声明: https://blog.csdn.net/ysq96/article/details/90026024

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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

题意:给定一个有序数组,在其中找到给定的target,找到就返回它在数组中的下标,如果没有找到就返回target应该插入的位置的下标

C++:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        auto it=find(nums.begin(),nums.end(),target);
        int i=0;
        if(it==nums.end()){
            for(i=0;i<nums.size();i++){
                if(nums[i]>target)break;
            }
        }else{
            for(i=0;i<nums.size();i++)
                if(nums[i]==target)break;
        }
        return i;
    }
};

Python3:

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        if target in nums:
            return nums.index(target)
        else:
            i=0
            for index in range(len(nums)):
                if nums[i]>target:
                    break
                i+=1
            return i

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/90026024