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

这个题目比较简单,意思就是查找里面某一个元素的位置,是二分查找的变种:


1.利用遍历的方法:

package leetcode;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: SearchIndex
 * @Description: TOTO
 * @date 2018/11/20 13:35
 **/


public class SearchIndex {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int key = 10;
        int index = searchIndex(arr, key);
        System.out.println(index);
    }

    private static int searchIndex(int[] nums, int target) {
        if (nums == null){
            return 0;
        }
        if (nums[nums.length - 1] < target) {
                return nums.length;
        }
        if (nums[0] >= target) {
            return 0;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] < target && nums[i + 1] >= target) {
                return i + 1;
            }
        }
        return -1;
    }
}

时间复杂度:O(n)

空间复杂度:O(1)


2.利用二分查找的方法:

package leetcode;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: SearchIndex2
 * @Description: TOTO
 * @date 2018/11/20 14:03
 **/


public class SearchIndex2 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 6, 7, 8, 10};
        int key = 9;
        int index = searchIndex(arr, key);
        System.out.println(index);
    }

private static int searchIndex(int[] nums, int target) {
        if (nums == null) {
            return 0;
        }
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            int middle = i + (j - i) / 2;
            if (nums[middle] > target) {
                j = middle - 1;
            } else if (nums[middle] < target) {
                if (nums[middle + 1] >= target) {
                    return middle + 1;
                } else {
                    i = middle + 1;
                }
            } else {
                return middle;
            }
        }
        if (nums[j] < target) {
            return j + 1;
        }
        return -1;
    }
}

时间复杂度:O(logn)

空间负责度:O(1)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84299628