leetCode 之SearchInsertPosition
来源:互联网 发布:前端面试题js 编辑:程序博客网 时间:2024/04/29 04:38
题目:
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.
其实就是查找的扩展
两种, 递归和迭代
// 递归public int searchPosition(int[] array,int start, int end ,int target){if(array[(end+start)/2] == target){return (end+start)/2;}if(end - start == 1 || end == start){if(array[start] < target){return start+1;}else{return start;}}if(array[(end+start)/2]>target){return searchPosition(array,start,(end+start)/2,target);}if(array[(end+start)/2]<target){return searchPosition(array,(end+start)/2+1,end,target);}return -1;}// 迭代public int searchPost(int[] array, int target){int end = array.length - 1;int start = 0;int index = 0;while(start <= end){index = (start+end)/2;if(array[index] == target)break;if(end - start == 1 || end == start){if(array[start]< target){index = start+1;}else{index = start;}break;}if(array[index] > target){end = index;}if(array[index] < target){start = index + 1;}}return index;}
0 0
- leetCode 之SearchInsertPosition
- LeetCode(34)SearchInsertPosition
- LeetCode 之
- LeetCode之Surrounded Regions
- LeetCode之Palindrome Partitioning
- LeetCode之Word Ladder
- leetcode之Same Tree
- leetcode之sqrt(x)
- leetcode之atoi
- leetcode之Reverse Integer
- leetcode之subsets
- leetcode之Path Sum
- leetcode之same tree
- leetcode之Plus One
- leetcode之Palindrome Partitioning
- leetcode之Valid Palindrome
- leetcode之Edit Distance
- leetcode之Gray code
- 学习XSLT(一)
- 关于Android读取不同位置(drawable,asset,SDCard)的图片资源的总结
- 栈、队列总结
- 学习XSLT(二)
- 【delphi】TComboBox 上下键选择值
- leetCode 之SearchInsertPosition
- 本科生教学评估
- 写程序的习惯与心得
- 数,数制
- .NET3.0 对象初始化器
- 关于软件开发---迭代开发
- 虚函数定义以及注意事项
- 神界危机3.4通关方略
- Android 自定义title