LeetCode 35 Search Insert Position 二分法处理
2016-06-08 00:00
411 查看
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.
解题思路:这道题目的意思是从序列中找到指定的target,返回index。若找不到,则返回插入该数的正确位置。因此,在前面整个就是基本的二分法处理,只有当找不到的时候,有r==l。分三种情况处理,左右指针在最左边界、最右边界以及中间某位置的三种情况处理。
代码如下:
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,返回index。若找不到,则返回插入该数的正确位置。因此,在前面整个就是基本的二分法处理,只有当找不到的时候,有r==l。分三种情况处理,左右指针在最左边界、最右边界以及中间某位置的三种情况处理。
代码如下:
public int searchInsert(int[] nums, int target) { int l = 0; int len = nums.length; int r = len-1; if(len == 1){ if(target<=nums[0]){ return 0; }else{ return 1; } } int mid =0; while(l<r){ mid = (l+r)/2; if(target==nums[mid]){ return mid; }else if(target>nums[mid]){ l = mid+1; }else{ r = mid-1; } } //左边界 右边界 中间 三种情况 if(l==0){ if(target<=nums[l]){ return 0; }else{ return 1; } }else if(l==len-1){ if(target>nums[l]){ return len; }else{ return len-1; } }else{ if(target>nums[l]){ return l+1; }else{ return l; } } }
相关文章推荐
- 学知识的时候,把自己放得低一点
- LeetCode Gas Station
- 函数指针的正确理解 from C++ Primer Plus P242
- Linux下CPU获取指定时间的用户态、系统态以及空闲态的时间
- LeetCode 39 && 40 Combination Sum I && II 关键在于剪枝,剪枝讨论在末尾
- php调用R的脚本实现方案
- Leetcode 55 Jump Game && 45 Jump Game II
- LeetCode 26 Remove Duplicates from Sorted Array
- LeetCode Repeated DNA Sequences的一点疑惑
- Max Sum Plus Plus----DP
- How does memmove differ from memcpy
- LeetCode 8 String to Integer (atoi)
- LeetCode 2 Add Two Numbers
- LeetCode 16 3Sum Closest
- BuildYourOwnLisp Why we need enum
- LeetCode 14 Longest Common Prefix 0ms实现的算法
- Fighting
- LeetCode 21 Merge Two Sorted Lists
- Win8+CentOS7 双系统安装恢复win8引导
- LeetCode 206 单链表逆置