1. 程式人生 > 實用技巧 >搜尋插入位置

搜尋插入位置

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

解題思路:

首先想到的就是遍歷整個陣列,查詢與目標值相等的數值,然後返回對應的索引,

如果陣列中不存在目標值,那就返回剛好比目標值大的索引

如果目標值是最大的,那麼直接返回陣列的長度

此時的兩個if需要使用break跳出,否則會接著與下邊的數值進行比較

程式碼實現:

 1 package easy;
 2 
 3 class SolutionSearch {
 4     public int searchInsert(int
[] nums, int value) { 5 int pos = 0; 6 int i = 0; 7 while(i < nums.length){ 8 if (nums[i] == value) { 9 pos = i; 10 break; 11 } else { 12 if (nums[i] > value) { 13 pos = i; 14
break; 15 } else { 16 pos = nums.length; 17 } 18 } 19 i ++; 20 } 21 return pos; 22 } 23 } 24 25 public class SearchInsert { 26 public static void main(String[] args) { 27 SolutionSearch solution = new SolutionSearch(); 28 int[] nums = {1,3,5,6}; 29 int value = 2; 30 System.out.println(solution.searchInsert(nums, value)); 31 } 32 }