[전] 두 개의 배열 을 정 하고 하나의 방법 을 써 서 그들의 교 집합 을 계산한다.

2550 단어 Leetcode
주어진 nums1 =  [1, 2, 2, 1] , nums2 =  [2, 2], 귀환  [2, 2] .
주의:
  •    출력 결과 에 있 는 모든 요소 가 나타 나 는 횟수 는 요소 가 두 배열 에 나타 나 는 횟수 와 일치 해 야 합 니 다.
  •    우 리 는 출력 결과 의 순 서 를 고려 하지 않 아 도 된다.

  • 따라 가기:
  • 주어진 배열 이 정렬 되 어 있다 면?당신 은 어떻게 당신 의 알고리즘 을 최적화 할 것 입 니까?

  • 하면, 만약, 만약... nums1 크기 nums2 많이 작 아 요. 어떤 방법 이 더 좋아요?
  • 만약 nums 2 의 요소 가 디스크 에 저장 된다 면 메모리 가 제한 되 어 있 습 니 다. 모든 요 소 를 메모리 에 한 번 에 불 러 올 수 없습니다. 어떻게 해 야 합 니까?

  • 주소:https://github.com/maronghe/ODOP/blob/master/src/com/logan/leetcode/intersect/IntersectTester.java
    
    public class IntersectTester {
    	
    	public static void main(String[] args) {
    		
    		int[] array1 = { 2, 1 };
    		int[] array2 = { 1, 2 };
    		int[] result = intersect(array1, array2);
    		for (Integer i : result) {
    			System.out.println(i);
    		}
    
    	}
    
    	/**
    	 * Count out number and number size. 
    	 * Judge whether the other array contains key.
    	 * 
    	 * @param nums1
    	 * @param nums2
    	 * @return result 
    	 */
    	public static int[] intersect(int[] nums1, int[] nums2) {
    
    		List list = new ArrayList();
    
    		Map map = new HashMap();
    
    		for (int i = 0; i < nums1.length; i++) {
    			Integer v = map.get(nums1[i]);
    			map.put(nums1[i], v == null ? 1 : (v + 1));
    		}
    
    		for (int j = 0; j < nums2.length; j++) {
    			// judge whether contains key
    			if (map.containsKey(nums2[j]) && map.get(nums2[j]) != 0) {
    				list.add(nums2[j]);
    				map.put(nums2[j], map.get(nums2[j]) - 1);
    			}
    		}
    
    		int[] result = new int[list.size()];
    
    		for (int k = 0; k < list.size(); k++) {
    			result[k] = list.get(k);
    		}
    
    		return result;
    	}
    
    	/**
    	 *  Sort array and judge whether equals from 0 to the smaller array's size
    	 *  this method is suitable for the large different size between two arrays. 
    	 * @param nums1
    	 * @param nums2
    	 * @return result 
    	 */
    	public static int[] intersect2(int[] nums1, int[] nums2) {
    		List list = new ArrayList();
    
    		Arrays.sort(nums1);
    		Arrays.sort(nums2);
    
    		int i = 0;
    		int j = 0;
    
    		if (i < nums1.length && j < nums2.length) {
    			if (nums1[i] == nums2[j]) {
    				list.add(nums1[i]);
    				j++;
    				i++;
    			} else if (nums1[i] > nums2[j]) {
    				j++;
    			} else if (nums1[i] < nums2[j]) {
    				i++;
    			}
    		}
    
    		int[] result = new int[list.size()];
    
    		for (int k = 0; k < list.size(); k++) {
    			result[k] = list.get(k);
    		}
    
    		return result;
    	}
    
    }
    

    좋은 웹페이지 즐겨찾기