編寫一個交錯合併列表元素的函式,兩種方法
阿新 • • 發佈:2019-02-15
//編寫一個交錯合併列表元素的函式。例如:給定的兩個列表為[a,B,C]和[1,2,3],函式返回[a,1,B,2,C,3]。
privatestatic String[] getStaggeredMergeArray(String[] arr1, String[] arr2)
{ String[] arr = new String[arr1.length + arr2.length];
int i, j; for (i = 0, j = 0; i < arr1.length; i++) {
j = 2 * i;
if (j > 2 * arr2.length)
j = arr2.length + i;
arr[j] = arr1[i];//0 2 4 }
for (i = 0, j = 0; i < arr2.length; i++) {
j = 2 * i + 1;
if (j > 2 * arr1.length)//若arr2陣列長度長等於arr1
j = arr1.length + i;
arr[j] = arr2[i];//1 3 5 }
return arr;}
publicstaticvoidmain(String[] args) {
String[] arr1 = {
String[] arr2 = { "1", "2", "3" };
String[] arr = getStaggeredMergeArray(arr1, arr2);
System.out.println(Arrays.toString(arr));}
- import java.util.*;
- publicclass Test2{
- publicstaticvoid main(String[] args){
-
ArrayList<Object> a1=new ArrayList<Object>();
- ArrayList<Object> a2=new ArrayList<Object>();
- a1.add('a');
- a1.add('B');
- a1.add('C');
- a2.add(1);
- a2.add(2);
- a2.add(3);
- a1.add(2.2);
- ArrayList<Object> a3=mergeList(a1,a2);
- System.out.println(a3);
- }
- publicstatic ArrayList<Object> mergeList(ArrayList<Object> a1,ArrayList<Object> a2){
- int size=a1.size()+a2.size();
- int j1=0,j2=0;
- ArrayList<Object> a3=new ArrayList<Object>();
- for(int i=0;i<size;i++){
- if(i%2==0)
- a3.add(a1.get(j1++));
- else
- a3.add(a2.get(j2++));
- }
- return a3;
- }
- }