LeetCode 35: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.

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

 

初看这题目,挺简单的,也没时间复杂度,最后嗨来了一句数组元素都不重复

package com.lihuia.leetcode;

/**
* Copyright (C), 2018-2019
* FileName: ThirtyFive
* Author: lihui
* Date: 2019-08-17
*/

public class ThirtyFive {

public int searchInsert(int[] nums, int target) {
int length = nums.length;
for (int i = 0; i < length; i++) {
if (nums[i] >= target) {
return i;
}
}
return length;
}
}

如果要用二分法

package com.lihuia.leetcode;

/**
* Copyright (C), 2018-2019
* FileName: ThirtyFive
* Author: lihui
* Date: 2019-08-17
*/

public class ThirtyFive {

public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
//{1,3,5,6} 2
while (left <= right) {
int middle = (left + right) / 2;
if (nums[middle] == target) {
return middle;
} else if (nums[middle] > target){
right = middle - 1;
} else {
left = middle + 1;
}
}
return left;
}
}

Python实现,同样山寨一版本

#!/usr/bin/env python

class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""

left = 0
right = len(nums) - 1
while left <= right:
middle = (left + right) / 2
if nums[middle] == target:
return middle
elif nums[middle] > target:
right = middle - 1
else:
left = middle + 1
return left

OVER

发表回复