1. 程式人生 > >35. 搜索插入位置

35. 搜索插入位置

pack tar 查找 lee sys class length des 一個

35. 搜索插入位置

https://leetcode-cn.com/problems/search-insert-position/description/

package com.test;

public class Lesson035 {
    public static void main(String[] args) {
        int[] nums = {1,3,5,6};
        int target = 5;
        int in = searchInsert(nums, target);
        System.out.println(in);
    }
    
public static int searchInsert(int[] nums, int target) { for(int i=0;i<nums.length;i++) { // 如果相等就找到了 if (target - nums[i]==0) { return i; } // 如果比第i個元素小 if (target < nums[i]) { // 如果比第一個元素小 if
(i == 0) { return 0; } // 如果比第i個元素小,並且比第i-1個元素大 if (i > 0 && target > nums[i - 1]) { return i; } } // 如果比第i個元素大 if (target > nums[i]) {
// 如果比最後一個元素大 if (i - nums.length == -1) { return nums.length; } // 如果比第i個元素大,並且比第i+1個元素小 if (i + 1 < nums.length && target < nums[i + 1]) { return i+1; } } } return 0; } }

二分查找:

技術分享圖片

35. 搜索插入位置