1.题目:包含重复(Contains Duplicate 2)
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
找到在距离k内是否有相等元素
思路:
暴力搜索
代码:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
for(int i=0;i<nums.size();++i)
for(int j=i+1;j<=std::min(i+k,(int)nums.size()-1);++j)
{
if(nums[i]==nums[j])
return true;
}
return false;
}
};
可以改进的地方:时间复杂度过高,O(nk)
改进的方法:
思路:利用哈希表, 以nums[i]为键,i为值。
使用unordered_map实现哈希表
代码:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int n=nums.size();
if(n<=0 || k<=0)
return false;
unordered_map<int,int> mp;
for(int i=0;i<n;++i)
{
if(mp.find(nums[i])!=mp.end() && (i-mp[nums[i]])<=k) //若找到相等的元素且间隔<=k
return true;
else //没找到或找到了但间隔>k,都将新的键值对存入
mp[nums[i]]=i;
}
return false;
}
};
2.题目:Isomorphic Strings(同构字符串)
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
判断两个相同长度的字符串是否有相同的结构。
思路:
和题目1类似,查找哈希表,若新的键值对与哈希表中的键值对的键和值有一个相同一个不同,则返回false;若均不同,则存入,均相同,不作为。将键值对的值均存入一个set,如果map的size比set大,说明有多个不同的键对应一个值。
代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int n=s.length();
if(n!=t.length())
return false;
unordered_map<char,char> mp;
set<char> st;
for(int i=0;i<n;++i)
{
if(mp.end()==mp.find(s[i]))
{
mp[s[i]]=t[i];
st.insert(t[i]);
if(mp.size()>st.size())
return false;
}
if(mp[s[i]]!=t[i])
return false;
}
return true;
}
};
可以改进的地方:运行时间有点长 24ms,若还有其他地方欢迎指出
改进的方法:(9ms)
思路:利用数组来存储两个字符串中相同位置字母出现位置
代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int m1[256] = {0}, m2[256] = {0}, n = s.size();//8位ASCII码表
for (int i = 0; i < n; ++i) {
if (m1[s[i]] != m2[t[i]]) return false;
m1[s[i]] = i + 1;
m2[t[i]] = i + 1;
}
return true;
}
};