Leetcode-35 Search Insert Position
来源:互联网 发布:世界十大灾难片 知乎 编辑:程序博客网 时间:2024/06/03 13:12
问题描述
地址:https://leetcode.com/problems/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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
翻译:给出排好序的数组和一个目标值(target),如果在数组中有这个target,则返回target的位置,如果数组中没有这个target,返回target应该在数组中的位置。
例如:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
问题解析
由于给出的数组是已经排序好的。所以这个问题可以归结为数组的查找问题,常用我们可以使用二分查找来完成。根据二分查找的一般步骤
(1)定义三个变量i,j,k,其中i指向数组的开始位置,j指向数组的结尾位置,k指向数组的中间位置。
(2)如果target>array[k],说明target必须在array[k]后面,这时候需要将i挪动到第k+1位置。
(3)如果target< array[k],说明target必须在array[k]前面,这时候将j挪动到第k-1位置。
解析代码
public class SearchInsertPosition { public static void main(String[] args) { //int[] array1 = {1,3,5,6};//5-2 int[] array1 = {1,2,4,5,6};//5-2 int[] array2 = {1,3,5,6};//2-1 int[] array3 = {1,3,5,6};//7-4 int[] array4 = {1,3,5,6};//0 -0 System.out.println(searchInsert(array1, 3)); } public static int searchInsert(int[] nums, int target) { int min = 0; int max = nums.length -1; while(min <= max){ int middle = (min + max)/2; if(nums[middle] == target){ return middle; } if(nums[middle] < target){ min = middle + 1; continue; } if(nums[middle] > target){ max = middle - 1; continue; } } return min; }}
- leetcode 35: Search Insert Position
- Leetcode(35) Search Insert Position
- [leetcode 35] Search Insert Position
- [Leetcode] 35 - Search Insert Position
- LeetCode 35 Search Insert Position
- leetcode-35 Search Insert Position
- LeetCode 35 Search Insert Position
- Leetcode 35 Search Insert Position
- Leetcode[35]-Search Insert Position
- LeetCode 35:Search Insert Position
- leetcode-35-Search Insert Position
- leetcode 35 -- Search Insert Position
- leetcode[35]:Search Insert Position
- leetcode 35: Search Insert Position
- Leetcode#35 Search Insert Position
- LeetCode(35) Search Insert Position
- LeetCode 35: Search Insert Position
- Leetcode#35||Search Insert Position
- 三天上手PHP之11:函数
- 介绍 Java 自带的线程池(1)
- [转载]使用EasyRTMP的Android版采集AAC音频流进行RTMP推送
- 2048游戏回顾一:使用SurfaceView创建游戏启动动画
- JQuery中$.ajax()方法参数详解
- Leetcode-35 Search Insert Position
- SSH框架环境配置以及登录功能的实现(通过注解)
- android 面向对象
- js,jQuery初学易出现问题
- PCB拼版设计
- 一个简单的python3爬虫
- robots.txt的作用
- Unreal Engine 4 C++ UCLASS构造函数易出错分析
- JAVA常用设计模式(2)工厂模式