題目連結
題意:
每組測資先給 n 與該 n 個數字
先求每兩兩相鄰的數字差(絕對值)
判斷這些結果形成的數列是否為 1 ~ n-1 的組合
是則輸出 Jolly, 否則 Not jolly
如:
1 4 2 3 有 4 個
|1-4| = 3
|4-2| = 2
|2-3| = 1
1 ~ 3 恰為 1 ~ n-1
因此為 Jolly
解法:
設一個 布林陣列(可以設上限,以防相減結果超過 n-1範圍)
紀錄兩兩相減的結果到陣列的 index
最後判斷 1 ~ n-1內是否存在沒紀錄的差值即可
程式(Java):
題意:
每組測資先給 n 與該 n 個數字
先求每兩兩相鄰的數字差(絕對值)
判斷這些結果形成的數列是否為 1 ~ n-1 的組合
是則輸出 Jolly, 否則 Not jolly
如:
1 4 2 3 有 4 個
|1-4| = 3
|4-2| = 2
|2-3| = 1
1 ~ 3 恰為 1 ~ n-1
因此為 Jolly
解法:
設一個 布林陣列(可以設上限,以防相減結果超過 n-1範圍)
紀錄兩兩相減的結果到陣列的 index
最後判斷 1 ~ n-1內是否存在沒紀錄的差值即可
程式(Java):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String args[]) { | |
Scanner sc = new Scanner(System.in); | |
while (sc.hasNext()) { | |
int n = sc.nextInt(); | |
boolean check[] = new boolean[3001]; | |
int num[] = new int[n]; | |
boolean jolly = true; | |
num[0] = sc.nextInt(); | |
for (int i = 1; i < n; i++) { | |
num[i] = sc.nextInt(); | |
check[Math.abs(num[i] - num[i-1])] = true; | |
} | |
for (int i = 1; i < n; i++) { | |
if (!check[i]) | |
jolly = false; | |
} | |
if (jolly) | |
System.out.println("Jolly"); | |
else | |
System.out.println("Not jolly"); | |
} | |
} | |
} |
留言
張貼留言