14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
解题思路:
以strs[0]为标准,LCP的长度必不超过strs[0]的长度,从前向后遍历。内层遍历所有的串,如果在所有串中都有strs[0][i],
就把它放到result中,否则返回。
string longestCommonPrefix(vector<string>& strs) {
int len = strs.size();
string result = "";
if (len == 0)
return result;
if (len == 1)
return strs[0];
if (strs[0] == "")
return strs[0];
for (int i = 0; i < strs[0].length(); i++) {
for (int j = 1; j < len; j++) {
if (strs[j].length() == i || strs[0][i] != strs[j][i])
return result;
}
result.push_back(strs[0][i]);
}
return result;
}
219. Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
解题思路:
使用unordered_map存储<nums[i], first_i>。如果当前i-first_i <= k,那就找到了。
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (k == 0)
return false;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); i++) {
if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k)
return true;
else
m[nums[i]] = i;
}
return false;
}