1. 程式人生 > >LeetCode:35. Search Insert Position(數字插入合適的位置)

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)