华为一道机试题

来源:互联网 发布:淘宝图片保护盾 编辑:程序博客网 时间:2024/05/16 12:52

问题描述:

 

比较两个数组,要求从数组最后一个元素开始逐个元素向前比较,如果2个数组长度不等,则只比较较短长度数组个数元素。请编程实现上述比较,并返回比较中发现的相等元素的个数。

 

代码:

 

 

package com.test.test;

public class Test {
 
 public static void main(String[] args) {
  int []a = {23,43,1,32,4,54,10,11,};
  int []b = {43,3,32,3,4,10,11};
  int alength = a.length;
  int blength = b.length;
  int count = 0;
  
  if (alength<=blength){
   for (int i = blength-1;i>(blength-alength-1) ; i--) {
    
     if(a[i-(blength-alength)]==b[i]){
      count++;
      System.out.println("相同的元素为"+b[i]);
     }

   }
  }else{
   
    for (int j = alength-1; j > (alength-blength-1); j--) {
     if(a[j]==b[j-(alength-blength)]){
      count++;
      System.out.println("相同的元素为"+a[j]);
     }
   
   }
  }
  
  System.out.println("相同的元素有"+count+"个");
  
 }

}

 

 

原创粉丝点击