leetcode-35-Search Insert Position

                                               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.

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

给你一个排好序的数字和一个target

如果target在数组里,就 返回它的下标

否则返回它插入此数组后的下标

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer}
    def searchInsert(self, nums, target): #python
        if target in nums:
            return nums.index(target)
        else:
            i=0
            while i


class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer}
    def searchInsert(self, nums, target): #python
        if target in nums:
            return nums.index(target)
        else:
            for x in nums:
                if target<=x:
                    return nums.index(x)
            else:return len(nums)  # 没有在循环体内退出 则插到了最后 


class Solution {
public:
    int searchInsert(vector& nums, int target) { //C++
        int i=0,n=nums.size();
        for(i=0;i



你可能感兴趣的:(LeetCode,leetcode)