# Sorting# Greedy# Array

c299 - 1. 連號或不連號

🔗 前往 ZeroJudge 原題

題目描述

題目要求判斷給定數列是否為連續整數。輸入一個由相異正整數組成的序列,輸出數列中的最小值和最大值,以及判斷數列是否為連續整數的結果("yes" 或 "no")。

解題思路

首先,對輸入的數列進行排序。然後,計算數列的最大值和最小值之間的差值。如果差值等於數列的長度減 1,則數列為連續整數,輸出 "yes",否則輸出 "no"。

複雜度分析

  • 時間複雜度: O(n log n) (主要來自排序)
  • 空間複雜度: O(n) (用於儲存輸入數列)

程式碼

#include <iostream>
#include <algorithm>

using namespace std;

int main(){
	
	int i=0;
	int max=0;
	bool ans=true;
	while(cin >> i){
		int n[i];
		for(int j=0;j<i;j++){
			cin >> n[j];
		}
		sort(n,n+i);
		cout << n[0] << " " << n[i-1] << " ";
		if(n[i-1]-n[0]!=i-1){
			ans=false;
		}
		if(ans==true){
			cout << "yes" << endl;
		}
		else{
			cout << "no" << endl;
		}
		ans=true;
		return 0;
	}
	
	
}

Discussion