当前位置:网站首页>[usual practice] explore the insertion position

[usual practice] explore the insertion position

2022-06-11 05:46:00 swindler.

Given a n The elements are ordered ( Ascending ) integer array nums And a target value target , Write a function search nums Medium target, If the target value has a return subscript , Otherwise return to -1.

Example 1:

Input : nums = [-1,0,3,5,9,12], target = 9
Output : 4
explain : 9 Appear in the nums And the subscript is 4
Example 2:

Input : nums = [-1,0,3,5,9,12], target = 2
Output : -1
explain : 2 non-existent nums So back to -1

Tips :

You can assume nums All elements in are not repeated .
n Will be in [1, 10000] Between .
nums Each element of will be in [-9999, 9999] Between .

class Solution {
    
    func searchInsert(_ nums: [Int], _ target: Int) -> Int {
    
        if nums.count == 1 {
    
            return target > nums[0] ? 1 : 0
        }
         if target > nums[nums.count - 1] {
    
           return nums.count 
       } 
       for i in 0...(nums.count - 1) {
    
           if nums[i] >= target {
    
               return i
           }
       }  
      
    return 0
    }
}

Their thinking :① First judge two special situations —— Only one element and target Value is greater than all array elements ;② Traversing array , And with target Comparison of values ;

原网站

版权声明
本文为[swindler.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020534563076.html