[leetcode]Search Insert Position
2016-01-19 17:37
260 查看
题目描述如下:
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
虽然是medium难度的题目,但其实就是一个二分搜索+最后的位置判断,实际上并不难,通过率不高可能是对位置判断有误。
代码如下:
题目链接: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
虽然是medium难度的题目,但其实就是一个二分搜索+最后的位置判断,实际上并不难,通过率不高可能是对位置判断有误。
代码如下:
public class Solution { public int searchInsert(int[] nums, int target) { int res = 0; if(nums.length == 0) return res; boolean isFind = false; int first = 0, last = nums.length - 1, mid; while(first < last){ mid = (first + last) / 2; if(nums[mid] == target){ res = mid; isFind = true; break; }else if(nums[mid] < target){ first = mid + 1; }else{ last = mid; } } if(!isFind){ if(last == nums.length - 1) { if(target > nums[nums.length - 1]) res = nums.length; else res = nums.length - 1 > 0 ? nums.length - 1 : 0; }else if(last == 0){ if(target > nums[0]) res = 1; else res = 0; }else{ if(target > nums[last]) res = last + 1; else res = last; } } return res; } }
题目链接:https://leetcode.com/problems/search-insert-position/
相关文章推荐
- ion-view 视图的生命周期及事件集合
- Command /usr/bin/codesign failed with exit code 1
- 进程间传递文件描述符
- 转载:UI设计师不可不知的安卓屏幕知识(原创文章)
- json.parse()和json.stringify()
- 用codeblock配置FLTK
- C# 拖拽按钮移动
- 为什么越来越多的网站域名不加www前缀?
- JAVA8 十大新特性详解
- 【Storm入门指南】第六章 真实示例
- 例题5-10 UVA 207 PGA Tour Prize Money PGA巡回赛的奖金
- const成员函数修改成员变量的问题
- IIS性能相关的配置、命令
- 学习Xapian(4) – Faceting Search(Filter)
- Git 工作流程介绍(二)
- 发现了一个超级棒的时间控件
- java 批量下载文件
- 浅谈iOS中MVVM的架构设计与团队协作
- 【Storm入门指南】第五章 Bolts
- python int方法