一次总结两道题,两道题目都比较基础
Description:Write a function to find the longest common prefix string amongst an array of strings.
分析: 这道题目最重要的知道什么叫prefix前缀, 否则一不小心就做成了最长子序列。前缀就是两个序列的前多少位
都要是一样的,不能跳着对齐,这样就比较简单了,也可以求很多个序列的公共前缀。
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
string result,comm;
if(strs.empty()) return result;
result= strs[];
for(int i=;i<strs.size();i++)
{
comm = "";
for(int j=;j<result.size();j++)
{
if(j>=strs[i].size()) break;
if(result[j]==strs[i][j]) comm.insert(comm.end(),result[j]);
else break;
}
result = comm;
} return result;
}
};
题目二:Search for a range
Description: Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
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(log n),则肯定是基于二分查找。因为有重复元素,则将二分查找
的边界条件变一下就可以了。
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> pos (,-) ;
if(n<=) return pos;
//left bound
int start=,stop = n-,mid;
while(start<=stop)
{
mid = (start+stop)/;
if(A[mid]==target && (mid== || A[mid-]<target))
{
pos[] = mid;
break;
}
else if(A[mid]<target)
{
start = mid+;
}
else{
stop = mid-;
}
}
if(pos[]==-) return pos;
//right bound
start=,stop = n-;
while(start<=stop)
{
mid = (start+stop)/;
if(A[mid]==target && (mid==n- || A[mid+]>target) )
{
pos[] = mid;
break;
}
else if(A[mid]>target)
{
stop = mid-;
}
else{
start = mid+;
}
}
return pos;
}
};