0%

June Leetcoding Challenge(6.10)

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.

You may assume no duplicates in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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在nums数组中存在,我们直接返回i的值,如果不存在,我们需要判断target的位置,如果他大于i却小于i+1,那么index为i+1.

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int searchInsert(int[] nums, int target) {
int index =0;
for(int i =0;i<nums.length;i++){
if(target == nums[i])
index = i;
else if(target>nums[i]){
if(i==nums.length-1 && target>nums[i])
index = nums.length;
else if(target<nums[i+1])
index = i+1;
}
}
return index;
}
}

Python代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def searchInsert(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;
-------------本文结束感谢您的阅读-------------

本文标题:June Leetcoding Challenge(6.10)

文章作者:Jungle

发布时间:2020年06月10日 - 09:11

最后更新:2020年06月11日 - 10:43

原始链接:http://yoursite.com/2020/06/10/LeetCode%E5%85%AD%E6%9C%88%E6%8C%91%E6%88%98%EF%BC%886.10%20)%20Search%20Insert%20Position%20LeetCode%2035/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Welcome to my other publishing channels