leetcode349,350,1查找表

349.png
    public int[] intersection(int[] nums1, int[] nums2) {

        HashSet record = new HashSet();
        for(int num: nums1)
            record.add(num);

        HashSet resultSet = new HashSet();
        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 record = new HashMap();
        for(int num: nums1)
            if(!record.containsKey(num))
                record.put(num, 1);
            else
                record.put(num, record.get(num) + 1);

        ArrayList result = new ArrayList();
        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 record = new HashMap();
        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");
    }

你可能感兴趣的:(leetcode349,350,1查找表)