【LeetCode】Search Insert Position 解题报告
来源:互联网 发布:ubuntu注销用户命令 编辑:程序博客网 时间:2024/05/29 02:58
【LeetCode】Search Insert Position 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/search-insert-position/#/description
题目描述:
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
Ways
我用了很愚蠢的方法,分两种情况进行遍历,算法复杂度是O(n).
public class Solution { public int searchInsert(int[] nums, int target) { int len = nums.length; int ans = 0; for(int i = 0; i < len; i++){ if(nums[i] == target){ ans = i; break; }else if((nums[i] < target && i < len - 1 && nums[i + 1] > target) || (nums[i] < target && i == len - 1)){ ans = i + 1; break; } } return ans; }}
但是,这个是有序的,可以用二分查找的方法。注意,如果查找到结果的要返回mid,没查找到的话返回的是left,因为这个时候left和right已经交叉了,left是比较靠右的位置,也就是应该插入的位置。
public class Solution { public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; int mid = 0; while(left <= right){ mid = (left + right) / 2; if(nums[mid] == target){ return mid; }else if(nums[mid] > target){ right--; }else{ left++; } } return left; }}
Date
2017 年 4 月 25 日
0 0
- LeetCode解题报告--Search Insert Position
- [leetcode] 35. Search Insert Position 解题报告
- [LeetCode] Search Insert Position 解题报告
- Leetcode解题报告:Search Insert Position
- [Leetcode] 35. Search Insert Position 解题报告
- 【LeetCode】Search Insert Position 解题报告
- [leetcode]解题报告35. Search Insert Position
- 【LeetCode】35.Search Insert Position解题报告
- Leetcode Search Insert Position解题报告
- Leetcode #35. Search Insert Position 搜寻插入位置 解题报告
- leetcode解题方案--035--Search Insert Position
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- mybatis generator
- 致我的第一篇博客
- 题目1433:FatMouse
- JAVA大数处理(BigInteger,BigDecimal)
- JSP(5)开发模式web-service等介绍
- 【LeetCode】Search Insert Position 解题报告
- The OCD Brain: how animal research helps us understand a devastating condition
- Java 枚举(enum)
- 数据库报错 Starting MySQL.The server quit without updating PID file (/usr/local/mysql/data/hostname.pid)
- git快捷键
- 题目1434:今年暑假不AC
- 数据库中查询2张表中某两个字段不同的数据
- 由“你好”引发的血案——调戏图灵机器人
- 个人一些感悟