LeetCode——哈希表
T1 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(hash.containsKey(target - nums[i])){
return new int[]{i, hash.get(target - nums[i])};
}
hash.put(nums[i], i);
}
return new int[0];
}
}
T128 最长连续序列
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> hash = new HashSet<Integer>();
for(int num : nums){
hash.add(num);
}
int longestLength = 0;
for(int num : nums){
if(!hash.contains(num - 1)){
int currentNum = num;
int currentLength = 1;
while(hash.contains(currentNum + 1)){
currentNum++;
currentLength++;
}
longestLength = Math.max(currentLength, longestLength);
}
}
return longestLength;
}
}
T149 直线上最多的点数
class Solution {
public int maxPoints(int[][] points) {
int n = points.length;
if (n <= 2) {
return n;
}
int ret = 0;
for (int i = 0; i < n; i++) {
if (ret >= n - i || ret > n / 2) {
break;
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int j = i + 1; j < n; j++) {
int x = points[i][0] - points[j][0];
int y = points[i][1] - points[j][1];
if (x == 0) {
y = 1;
} else if (y == 0) {
x = 1;
} else {
if (y < 0) {
x = -x;
y = -y;
}
int gcdXY = gcd(Math.abs(x), Math.abs(y));
x /= gcdXY;
y /= gcdXY;
}
int key = y + x * 20001;
map.put(key, map.getOrDefault(key, 0) + 1);
}
int maxn = 0;
for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
int num = entry.getValue();
maxn = Math.max(maxn, num + 1);
}
ret = Math.max(ret, maxn);
}
return ret;
}
public int gcd(int a, int b) {
return b != 0 ? gcd(b, a % b) : a;
}
}
T332 重新安排行程
2、判断数组是否含有重复元素
T217 Contains Duplicate (Easy)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> m;
for(int i=0; i<nums.size(); ++i){
if(m.find(nums[i]) != m.end()) return true;
++m[nums[i]];
}
return false;
}
};
3、最长和谐序列
T594 Longest Harmonious Subsequence (Easy)
class Solution {
public:
int findLHS(vector<int>& nums) {
map<int, int> m;
int res=0;
for(int num:nums) ++m[num];
for(auto a:m){
if(m.count(a.first+1)){
res=max(res, m[a.first]+m[a.first+1]);
}
}
return res;
}
};