leetcode349,350,1查找表
2019-06-07 本文已影响0人
__hgb
349.png
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> record = new HashSet<Integer>();
for(int num: nums1)
record.add(num);
HashSet<Integer> resultSet = new HashSet<Integer>();
for(int num: nums2)
if(record.contains(num))
resultSet.add(num);
int[] res = new int[resultSet.size()];
int index = 0;
for(Integer num: resultSet)
res[index++] = num;
return res;
}
350.png
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int num: nums1)
if(!record.containsKey(num))
record.put(num, 1);
else
record.put(num, record.get(num) + 1);
ArrayList<Integer> result = new ArrayList<Integer>();
for(int num: nums2)
if(record.containsKey(num) && record.get(num) > 0){
result.add(num);
record.put(num, record.get(num) - 1);
}
int[] ret = new int[result.size()];
int index = 0;
for(Integer num: result)
ret[index++] = num;
return ret;
}
1.png
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int i = 0 ; i < nums.length; i ++){
int complement = target - nums[i];
if(record.containsKey(complement)){
int[] res = {i, record.get(complement)};
return res;
}
record.put(nums[i], i);
}
throw new IllegalStateException("the input has no solution");
}