hot100
两数之和
题目链接:
1.两数之和
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
int n = nums.length;
for (int i = 0; i < n; i ++)
{
if (map.containsKey(target-nums[i]))
{
return new int[] {map.get(target - nums[i]),i};
}
map.put(nums[i],i );
}
return null;
}
}
字母异位词分组
题目链接:
49.字母异位词分组
代码:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for (String str:strs){
char[] array = str.toCharArray();
Arrays.sort(array);
String key = new String(array);
List<String> list = map.getOrDefault(key, new ArrayList<String>());
list.add(str);
map.put(key,list);
}
return new ArrayList<List<String>>(map.values());
}
}
最长连续序列
题目链接:
128.最长连续序列
代码:
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i ++)
{
set.add(nums[i]);
}
int len = 0;
for (int s:set)
{
if (!set.contains(s - 1))
{
int curr = 1;
int currnum = s;
while (set.contains(currnum + 1))
{
curr ++;
currnum ++;
}
len = Math.max(len,curr);
}
}
return len;
}
}