java – 组合来自2个数组的唯一整数的最快方法
发布时间:2020-12-15 08:47:59 所属栏目:Java 来源:网络整理
导读:如果我有2个数组: arr1 = {9,8}arr2 = {13,12,10,9,8} 我想得到: {13,10} 并给出阵列: arr1 = {23,22,21,20,19,18,17,16}arr2 = {21,17} 结果将是: {23,16} 所以基本上我得到的数字是arr1或arr2,但不是两者. 2个阵列可能有不同的长度. 2个数组按降序排序
如果我有2个数组:
arr1 = {9,8} arr2 = {13,12,10,9,8} 我想得到: {13,10} 并给出阵列: arr1 = {23,22,21,20,19,18,17,16} arr2 = {21,17} 结果将是: {23,16} 所以基本上我得到的数字是arr1或arr2,但不是两者. > 2个阵列可能有不同的长度. 解决方法
你正在寻找两套的EXOR.由于阵列是预先排序的,我认为这比它看起来更简单.伪代码
这是一个greedy O(n)解决方案.这是一个实施,经过轻微测试:D /** * Returns the sorted EXOR of two sorted int arrays (descending). Uses * arrays,index management,and System.arraycopy. * @author paislee */ int[] arrExor(int[] a1,int[] a2) { // eventual result,intermediate (oversized) result int[] exor,exor_builder = new int[a1.length + a2.length]; int exor_i = 0; // the growing size of exor set int a1_i = 0,a2_i = 0; // input indices int a1_curr,a2_curr; // elements we're comparing // chew both input arrays,greedily populating exor_builder while (a1_i < a1.length && a2_i < a2.length) { a1_curr = a1[a1_i]; a2_curr = a2[a2_i]; if (a1_curr != a2_curr) { if (a1_curr > a2_curr) exor_builder[exor_i++] = a1[a1_i++]; else exor_builder[exor_i++] = a2[a2_i++]; } else { a1_i++; a2_i++; } } // copy remainder into exor_builder int[] left = null; // alias for the unfinished input int left_i = 0,left_sz = 0; // index alias,# elements left if (a1_i < a1.length) { left = a1; left_i = a1_i; } else { left = a2; left_i = a2_i; } left_sz = left.length - left_i; System.arraycopy(left,left_i,exor_builder,exor_i,left_sz); exor_i += left_sz; // shrinkwrap and deliver exor = new int[exor_i]; System.arraycopy(exor_builder,exor,exor_i); return exor; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |