[leedcode]–35. Search Insert Position
来源:互联网 发布:java摇奖机转盘 编辑:程序博客网 时间:2024/05/16 10:54
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
/* 错误的解法,应该摒弃这种错误的想法 for(int i =0;i<nums.length;i++){ if(i == nums.length-1){ return nums.length; }else if(nums[0]>target){ return 0; } else if(nums[i]<target&&nums[i+1]>target){ return i+1; }else if(nums[i]>target&&nums[i+1]>target){ return i-1; }else if(nums[i] == target){ return i; } } return 0;*/ //其实就是二分法插入数据即可解决 int low =0,high=nums.length-1; int mid ; while (low<=high){ mid=(low+high)/2; if(nums[mid] == target) return mid; else if(nums[mid]<target) low = mid+1; else high = mid-1; } return low;
阅读全文
1 0
- [leedcode]–35. Search Insert Position
- LeedCode 之 Search Insert Position
- [LeedCode OJ]#35 Search Insert Position
- 35.Search Insert Position
- 35. Search Insert Position
- 35.Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- HashCode的理解与应用
- MATLAB2015b链接MinGW编译器
- 【NOIP模拟赛三】并查集+hash day2 third 雪后村庄(好题)
- 机器学习:朴素贝叶斯算法+中文情感分类+python
- Girls and Boys
- [leedcode]–35. Search Insert Position
- bzoj 2969: 矩形粉刷 期望
- javascript面向对象属性函数用法(defineProperty与getOwnPropertyDescriptor)
- CountDownLatch和CyclicBarrier
- 301与302
- Java的冒泡排序
- Volley应用与源码分析(一)
- POJ 2236 ——Wireless Network(并查集的应用)
- 通用分页查询