Skip to content

Commit

Permalink
map的一些写法思考
Browse files Browse the repository at this point in the history
  • Loading branch information
Xikl committed Dec 28, 2018
1 parent e38e979 commit a07a58d
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.ximo.datastructuresinaction.leetcode.solution349;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author xikl
* @date 2018/12/28
*/
public class Solution {


public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());

set1.retainAll(set2);


return set1.stream().mapToInt(Integer::intValue).toArray();
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.ximo.datastructuresinaction.leetcode.solution350;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
* @author xikl
* @date 2018/12/28
*/
public class Solution {

public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();

for (int num : nums1) {
// if (!map.containsKey(num)) {
// map.put(num, 1);
// } else {
// map.put(num, map.get(num) + 1);
// }

map.compute(num, (key, value) -> value == null ? 1 : value + 1);
}

List<Integer> list = new LinkedList<>();
for (int num : nums2) {
// if (map.containsKey(num)) {
// list.add(num);
// map.put(num, map.get(num) - 1);
// if (map.get(num) == 0) {
// map.remove(num);
// }
// }
map.computeIfPresent(num, (key, value) -> {
list.add(key);
value = value - 1;
if (value == 0) {
map.remove(key);
}
return value;
});
}

return list.stream().mapToInt(Integer::intValue).toArray();
}


}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ximo.datastructuresinaction.leetcode.Solution804;
package com.ximo.datastructuresinaction.leetcode.solution804;

import java.util.Set;
import java.util.TreeSet;
Expand Down

0 comments on commit a07a58d

Please sign in to comment.