[전] 두 개의 배열 을 정 하고 하나의 방법 을 써 서 그들의 교 집합 을 계산한다.
2550 단어 Leetcode
[1, 2, 2, 1] , nums2 = [2, 2], 귀환 [2, 2] . 주의:
따라 가기:
하면, 만약, 만약... nums1 크기 nums2 많이 작 아 요. 어떤 방법 이 더 좋아요?
주소: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;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
LeetCode 문제풀이 노트 113.경로 총 II경로 총 II 제목 요구 사항 문제풀이 두 갈래 나무와 목표와 뿌리 노드에서 잎 노드까지의 모든 경로를 찾는 것은 목표와 같은 경로입니다. 설명: 잎 노드는 하위 노드가 없는 노드를 가리킨다. 예: 다음과 같은 두 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.