2ms Java Solution


  • 0
    H

    The solution takes 2ms. Basically, It's hash. Hash i to hashArray[i] as 1.
    The code is as follow.

    public class Solution {
        public int max(int nums[]){
            int maxNumber = 0;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] > maxNumber){
                    maxNumber = nums[i];
                }
            }
            return maxNumber;
        }
        
        public int[] intersection(int[] nums1, int[] nums2) {
            //The number of intersection nums
            int count = 0;
            int maxNumber = (max(nums1) >= max(nums2))? max(nums1): max(nums2);
            
            int[] hashArray = new int[maxNumber + 1];
            for(int i = 0; i < maxNumber + 1; i++){
                hashArray[i] = 0;
            }
            for(int i = 0; i < nums1.length; i++){
                if(hashArray[nums1[i]] != 1){
                    hashArray[nums1[i]] = 1;
                }
            }
            for(int i = 0; i < nums2.length; i++){
                if(hashArray[nums2[i]] != -1){
                    if(hashArray[nums2[i]] == 1){
                        hashArray[nums2[i]] = -1;
                        count++;
                    }
                }
            }
            int[] result = new int[count];
            int index = 0;
            
            for(int i = 0; i < maxNumber + 1; i++){
                if(hashArray[i] == -1){
                    result[index] = i;
                    index++;
                }
            }
            return result;
        }
    }
    

  • 0
    C

    @haosunuiuc what if the nums1 has negative num? such as [-2,-3,1]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.