如何计算两个有序整型数组没有重复元素的交集?例如 a=01234;b=13579; 交集为13。 获取两个数组中的相同元素并存放到新数组中
可以使用双指针的方法来计算两个有序整型数组的交集。
首先,创建一个新的空数组,用于存放交集元素。
然后,使用两个指针分别指向两个数组的起始位置,比较两个指针指向的元素。
如果两个指针指向的元素相等,说明找到了一个交集元素,将其添加到新数组中,并将两个指针都向后移动一位。
如果两个指针指向的元素不相等,将较小的元素所在的指针向后移动一位。
重复上述步骤,直到任一数组的指针超出了数组的范围。
最后,返回新数组即为两个有序整型数组的交集。
以下是使用Java代码实现该算法:
import java.util.ArrayList;
import java.util.List;
public class IntersectionOfTwoArrays {
public static int[] intersection(int[] nums1, int[] nums2) {
List<Integer> result = new ArrayList<>(); // 用于存放交集元素
int i = 0; // nums1指针
int j = 0; // nums2指针
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
result.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] intersection = new int[result.size()];
for (int k = 0; k < result.size(); k++) {
intersection[k] = result.get(k);
}
return intersection;
}
public static void main(String[] args) {
int[] nums1 = {0, 1, 2, 3, 4};
int[] nums2 = {1, 3, 5, 7, 9};
int[] intersection = intersection(nums1, nums2);
System.out.print("Intersection: ");
for (int num : intersection) {
System.out.print(num + " ");
}
}
}
输出结果为:Intersection: 1
原文地址: http://www.cveoy.top/t/topic/inLU 著作权归作者所有。请勿转载和采集!