题目:在一串有序数组中,给出一串随机数组查找其中不同的部分
数组A:{2,3,5,8,9,11}
数组B:{9,8,2,10,1}
结果:10,1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class GetAllNotIncluded {
// 利用二分查找查找与子串不同的部分
public static List<Integer> getAllNotIncluded(int A[], int B[]) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < B.length; i++) {
int L = 0;
int R = A.length - 1;
boolean flag = false;
while (L <= R) {
int mid = L + ((R - L) >> 1);
if (A[mid] == B[i]) {
flag = true;
break;
}
if (A[mid] > B[i]) {
R = mid - 1;
} else {
L = mid + 1;
}
}
if (!flag) {
res.add(B[i]);
}
}
return res;
}
//比较函数
public static List<Integer> comparator(int A[],int B[]){
List<Integer> res =new ArrayList<>();
for(int i=0;i<B.length;i++) {
boolean flag=false;
for(int j=0;j<A.length;j++) {
if(A[j]==B[i]) {
flag=true;
break;
}
}
if(!flag) {
res.add(B[i]);
}
}
return res;
}
//获取随机数组
public static int[] getRandomArray(int maxSize,int maxValue) {
int[] arr=new int[(int)((maxSize+1)*Math.random())];
for(int i=0;i<arr.length;i++) {
//获取 -maxVlaue + 1 ~ maxValue 的值
arr[i]=(int)((maxValue+1)*Math.random())-(int)(maxValue*Math.random());
}
return arr;
}
public static boolean isEqual(List<Integer> list1,List<Integer> list2) {
if(list1.size()!=list2.size()) {
return false;
}
HashMap<Integer,Integer> map=new HashMap<>();
for(Integer i : list1) {
//如果没有A集合中的这个元素,则添加进集合
if(!map.containsKey(i)) {
map.put(i, 0);
}
//如果存在即更新对应value值
map.put(i,map.get(i)+1);
}
for(Integer i:list2) {
//如果不存在,则直接return false
if(!map.containsKey(i)) {
return false;
}
//如果重复存在的值 数量不同
map.put(i,map.get(i)-1);
if(map.get(i)<0) {//即第二个集合数量重复值多于第一个集合
return false;
}
}
return true;
}
public static void main(String[] args) {
int tests =50000;
//有序的数组最大长度
int sortedArrayMaxSize = 300;
//未排序的数组最大长度
int unsortedArrayMaxSize = 10;
//变量范围
int maxValue = 100;
boolean flag = true;
for (int i = 0; i < tests; i++) {
int[] A = getRandomArray(sortedArrayMaxSize, maxValue);
int[] B = getRandomArray(unsortedArrayMaxSize, maxValue);
//二分查找-有序数组
Arrays.sort(A);
List<Integer> res1 = getAllNotIncluded(A, B);
List<Integer> res2 = comparator(A, B);
if (!isEqual(res1, res2)) {
flag = false;
break;
}
}
System.out.println(flag ? "Nice!" : "Fucking fucked!");
//例
int A[]= {8,5,6,8,2,8,2,3,5,4,5,6,7,9,9,3,2,11,2,21,26};
int B[]= {1,2,2,3,4,10};
Arrays.sort(A);
List<Integer> res1 = getAllNotIncluded(A, B);
List<Integer> res2 = comparator(A, B);
Iterator it1=res1.iterator();
Iterator it2=res1.iterator();
while(it1.hasNext()) {
System.out.print(it1.next()+" ");
}
System.out.println();
while(it2.hasNext()) {
System.out.print(it2.next()+" ");
}
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有