

看題目很容易想到以下代碼
public class Main {
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
List<Integer>list=new ArrayList<>();
for(int i=0;i<n;i++) {
Integer num=sc.nextInt();
while(list.contains(num)) {
num++;
}
list.add(num);
}
System.out.println(list);
sc.close();
}
}
但是這樣只能處理較少情況,遇到特殊數肯定會超時,下面的這種處理方法優化了不少,不是每次+1了,而是直接加相同數字出現過的次數,比如有3個1,第二個1就是+1,第三個直接+2,而不是兩次+1,而且每次都記錄每次的新值出現的次數,這樣回圈到新數未出現過為止,
public class Main {
static int[] a1 = new int[1000010], a2 = new int[1000010];//一個用于輸出,一個用于儲存節點
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i = 0; i < a; i++) {
int count = sc.nextInt();
for (;;) //回圈遍歷
{
if (a2[count] == 0) { //確定輸入的值是否已經存在
a2[count]++;//若不存在則標記推出回圈
break;
}else {
a2[count]++;//若存在則為該標識訪問次數加一減少回圈次數
count +=a2[count] - 1;
}
}
a1[i] = count;
}
for (int i = 0; i < a; i++) {
System.out.print(a1[i] + " ");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/276750.html
標籤:java
上一篇:一萬字一篇文20分鐘學會C語言和Python,十四年編程經驗老鳥傳授經驗之道
下一篇:普歌-日期相關類、包裝類
