一组元素的存放
——以一组n个数字为例,数字从键盘上输入
创建一维数组
——最熟悉最普通的方式
int[] txet = new int[n]; //创建一个大小为 n(已知大小) 的整形数组 txet
for(int i = 0; i < 100; i++)
text[i] = scan.nextInt(); //利用循环读入键盘输入的整形进行保存。
/*
************
*/
数组的大小: int n = txet.length。数组的大小为n
散列表
——HashSet< T>hs = new HashSet< T>(); 在util下,需要导包
特点:
①无序性,无索引(下标),无重复
②用于快速查找
③用三列函数确定元素位置,三列函数: y = f(key)
HashSet<Integer> hs = new HashSet<Integer>(); //创建一个散列表对象 hs
for(int i = 0; i < n; i++)
hs.add( txet[i] ); //将数组 txet 中的元素赋给 散列表 hs 中;重复的不储存
/*
*****************************
*/
散列表 hs 的大小为 int t = hs.size(); t 就是散列表 hs 的长度
④输出
第一种:迭代器输出
Iterator iter = hs.iterator(); //产生迭代器,在util下,需要导包。
while(iter.hasNext()){ //判断是否有下一个元素。 hasNext()方法相当于指针。
Integer value = (Integer)iter.next(); //获取元素
System.out.print(value+" ");
}
第二种:增强型 for 循环
for(Int num : hs) //遍历
System.out.print( num + " ");
Java List 接口
—— Java Collections Framework 的成员,在util下,需要导包
详细内容(转载自 IT码客)
/*
*******************************************************************************************************
*******************************************************************************************************
*******************************************************************************************************
*******************************************************************************************************
*******************************************************************************************************
*******************************************************************************************************
*/
编写程序处理 有重复的数据
题意:在一大堆数据中找出重复的是一件经常要做的事情。现在,我们要处理许多整数,在这些整数中,可能存在重复的数据。你要写一个程序来做这件事情,读入数据,检查是否有重复的数据。如果有,输出“YES”这三个字母;如果没有,则输出“NO”。
用数组的方法:
此方法运行时间长,易超时
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner cs = new Scanner(System.in);
int n = cs.nextInt(), i = 0, j = 0, b = 0, t = 0;
int[] a = new int[n];
for (i = 0; i < n; i++) {
a[i] = cs.nextInt();
}
for (i = 0; i < n - 1; i++) {
b = a[i];
for (j = i + 1; j < n; j++) {
if (b == a[j]) {
t++;
break;
}
}
if (t != 0)
break;
}
if (t != 0)
System.out.println("YES");
else
System.out.println("NO");
}
}
用散列表的方法
运行时间短,减少for循环
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner cs = new Scanner(System.in);
int n = cs.nextInt(), i = 0;
int[] a = new int[n];
HashSet<Integer>hs = new HashSet<Integer>();
for (i = 0; i < n; i++) {
a[i] = cs.nextInt();
hs.add(a[i]);
}
if(hs.size()==a.length)
System.out.println("NO");
else
System.out.println("YES");
}
}