把大小王当做0.然后对整个序列排序。排序后计算大小王的数目和需要大小王填的坑的数目。如果大小王数目大于等于要填的坑的数目就返回真,否则返回假。
1 class Solution { 2 public: 3 bool IsContinuous(vector<int> numbers) { 4 if (numbers.empty()) 5 return false; 6 sort(numbers.begin(), numbers.end()); 7 //count:需要填的坑的数目,king:大小王数目 8 int count = 0,king=0; 9 for (int i = 0; i < numbers.size(); i++) 10 { 11 if (numbers[i] == 0) 12 { 13 king++; 14 continue; 15 } 16 if (i < numbers.size() - 1) 17 { 18 int temp = numbers[i + 1] - numbers[i]; 19 if (temp > 1) 20 count += temp-1; 21 else 22 if (temp == 0) 23 return false; 24 } 25 } 26 cout << count <<" "<<king<< endl; 27 if (count <= king) 28 return true; 29 else 30 return false; 31 } 32 };
原文地址:https://www.cnblogs.com/neverland0718/p/11211662.html
时间: 2024-10-30 00:23:48