作业一:数据结构与算法基础
判断数组中所有的数字是否只出现一次。给定一个数组array,判断数组 array 中是否所有的数字都只 出现过一次。例如,arr = {1, 2, 3},输出 YES。又如,arr = {1, 2, 1},输出 NO。约束时间复杂度为 O(n)。
理题
判断一系列数中的数字是否都只出现过一次,或者判断一系列数中的数字是否有重复出现过。
都只出现过一次则输出yes,否则输出no。
思路一
两两相比,时间复杂度为O(n^2)
思路二
排序加前后比较是否相等,时间复杂度为O(n^2)
思路三
遍历数组,存储到map中,并记录出现次数,当某个数已经存在时,则标志存在重复的数字。O(n),但是会占用额外的空间。
public static void main(String[] args) {
test1();
}
public static void test1(){
int arr[] = {
-1,1, 2, -1};
HashMap<String,Integer> hm=new HashMap<String, Integer>(arr.length);
boolean flag=false;
for(int a:arr) {
String key=a+"";
if(hm.containsKey(key)){
hm.put(key,hm.get(key)+1);
flag=true;
System.out.println(key);
}else{
hm.put(key,1);
}
}
if(