第九周算法分析与设计: Search for a Range
2017-04-21 22:57
519 查看
问题描述:
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(logn).
If the target is not found in the array, return
For example,
Given
return
问题来自此处
解答思路:
一看到题目要求时间复杂度是O(logn),又是跟查找相关的,还能想到什么办法呢~当然是
我的思路是先找到目标数,然后往目标数的左右分别延伸查找,定下相同数所在的上下界。
写得很煞笔。。我以为运行时间的排名铁定会被排在最后那批。。结果居然在中间……有毒有毒~
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(logn).
If the target is not found in the array, return
[-1, -1].
For example,
Given
[5, 7, 7, 8, 8, 10]and target value 8,
return
[3, 4].
问题来自此处
解答思路:
一看到题目要求时间复杂度是O(logn),又是跟查找相关的,还能想到什么办法呢~当然是
二分法啦!
我的思路是先找到目标数,然后往目标数的左右分别延伸查找,定下相同数所在的上下界。
vector<int> searchRange(vector<int>& nums, int target) { vector<int> result(2,-1); //初始化为[-1,-1] int size = nums.size(); if(size == 0){ return result; } int low = 0, high = size - 1, med; while(low <= high){ med = (low + high) / 2; if(nums[med] == target){ int left = find_bound(nums,0,med,target); int right = find_bound(nums,size,med,target); result.clear(); result.push_back(left); result.push_back(right); return result; } else if(nums[med] < target){ low = med + 1; } else{ high = med - 1; } } return result; } int find_bound(vector<int> nums,int numb,int med,int target){ int res = med; if(numb<=med){ for(int i = med;i >= numb;i--){ if(nums[i] == target) res = i; if(nums[i] < target) break; } } else{ for(int i = med;i < numb;i++){ if(nums[i] == target) res = i; if(nums[i] > target) break; } } return res; }
写得很煞笔。。我以为运行时间的排名铁定会被排在最后那批。。结果居然在中间……有毒有毒~
相关文章推荐
- 算法分析与设计课程(5):【leetcode】Search for a Range
- 算法分析与设计课程——LeetCode刷题之Search for a Range
- 第三周算法分析与设计:Search in Rotated Sorted Array
- 算法分析与设计第九周:45. Jump Game II
- 算法分析与设计第五周习题:95. Unique Binary Search Trees II
- 算法分析与设计——LeetCode Problem.598 Range Addition II
- 算法分析与设计——LeetCode Problem.33 Search in Rotated Sorted Array
- 算法课第十四周作业 | Search for a Range
- 算法分析与设计——LeetCode:33. Search in Rotated Sorted Array
- 算法分析与设计——LeetCode Problem.35 Search Insert Position
- 【LeetCode-面试算法经典-Java实现】【034-Search for a Range(搜索一个范围)】
- 【算法分析与设计】【第九周】91. Decode Ways
- [算法分析与设计] leetcode 每周一题: Validate Binary Search Tree
- python写算法题:leetcode: Add to List 34. Search for a Range
- 算法分析与设计课程作业第九周#1#2#3
- 算法系列——Search for a Range
- 【LeetCode题意分析&解答】34. Search for a Range
- 算法分析与设计——LeetCode Problem.98 Validate Binary Search Tree
- (算法设计技巧与分析)LinearSearch
- 【算法设计与分析】经典代码赏析【1】