有一个数组M有一些数据,另一个数组N也有一些数据,M中的一些数据N中也有,请有最少循环找出相同的数据
我有了一个方法.
package com.xlh.dao;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class SecondFind {
static int[] M = new int[] { 2, 4, 5, 8, 65, 81 };
static int[] N = new int[] { 8, 5, 45, 57, 89, 6, 4, 65, 1, 5, 2 };
static HashMap m = new HashMap();
static int count = 0;
public static void main(String[] args) {
// 输出M和N的长度
System.out.println("M的长度为=" + M.length);
System.out.println("N的长度为=" + N.length);
// find(M,N) ;
// 试试哈希表
hash();
System.out.println("循环了多少次count=" + count);
}
//哈希算法
public static void hash() {
for (int i = 0; i < M.length; i++) {
m.put(i, M[i]);
count++;
}
for (int i = 0; i < N.length; i++) {
//将N的数放到M哈希表的时候判断一下是否有一样的.
if (m.containsValue(N[i])) {
System.out.println("N["+i+"]="+N[i]) ;
} else {
m.put(count,N[i]) ;
}
count++ ;
}
}
// 先用最笨的方法
public static void find(int[] a, int[] b) {
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < N.length; j++) {
if (M[i] == N[j]) {
System.out.println(M[i]);
// break ;
}
count++;
}
}
}
}