LeetCode六月挑战(6.10 ) Search Insert Position LeetCode 35
Solution 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.
classSolution{ publicintsearchInsert(int[] nums, int target){ int index =0; for(int i =0;i<nums.length;i++){ if(target == nums[i]) index = i; elseif(target>nums[i]){ if(i==nums.length-1 && target>nums[i]) index = nums.length; elseif(target<nums[i+1]) index = i+1; } } return index; } }
Python代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defsearchInsert(self, nums: List[int], target: int) -> int: index =0; x = len(nums)-1; for i in range (-1,x+1): if nums[i] == target: index = i; else: if i == x and nums[i] < target: index = x+1; else: if target > nums[i] and target < nums[i+1]: index = i+1 return index;