搜索插入位置
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 }
无为之事,不言之教

浙公网安备 33010602011771号