LeetCode
来源:互联网 发布:java生成带参数二维码 编辑:程序博客网 时间:2024/06/15 10:58
题目:
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.
思路与步骤:
其实就是一个查找问题。
这里写出了顺序查找,学习并实现了折半查找。其他查找方法待以后学习了查找算法再继续。
编程实现:
顺序查找:
public class Solution { public int searchInsert(int[] nums, int target) { // SequentialSearch int i = 0; while(i<nums.length && target>nums[i]) i++; return i;}
折半查找:
public class Solution { public int searchInsert(int[] nums, int target) { // BinarySearch if(nums.length==1) return target > nums[0] ? 1 : 0; int begin = 0, end = nums.length-1, mid = (begin+end)/2; while(begin <= end){ mid = (begin+end)/2; if(target == nums[mid]) return mid; else if(target < nums[mid]) end = mid-1; else if(target > nums[mid]) begin = mid+1; } if(target < nums[mid]) return mid; else return mid+1; }}
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 系统性能测试及调优
- Nginx 战斗准备 —— 优化指南
- <<C++代码设计与重用>>读书笔记(一) Nice 类
- Lua中的loadfile、dofile、require详解
- ThreadLocal详解
- LeetCode
- Linux内核的原子操作
- Python 类装饰器
- SQLyog v12.09版本注册码
- 代码签名探析
- IOS基础学习之C(一)
- 使用继承与多态思想编写矩形,等边三角形,圆,求周长与面积
- 吐血分享android学习,安卓资源,自学资源
- 金额计算以及格式转换