gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
用C语言编写一段简单代码,题目要求为:…
- User
用C语言编写一段简单代码,题目要求为: 最長嚴格遞增子數列:寫一個程式,自一串整數中找出最長的嚴格遞增子字串,即是從原一串整數中,找到一個子集合;按照原來的順序排列時,是下一個比前一個值大,並且此子集合個數會最大(即排出來的子字串最長)。 例如: 輸入 -17 11 9 2 3 8 8 10 -1 6 4 2
輸出 -17 2 3 8 10
- Assistant
以下是用C语言编写的解决方案:
#include <stdio.h> int main() { int nums[] = {-17, 11, 9, 2, 3, 8, 8, 10, -1, 6, 4, 2}; int n = sizeof(nums) / sizeof(nums[0]); int start = 0, end = 0, maxLength = 0; for (int i = 1; i < n; i++) { if (nums[i] > nums[i-1]) { end = i; } else { if (end - start + 1 > maxLength) { maxLength = end - start + 1; } start = i; end = i; } } if (end - start + 1 > maxLength) { maxLength = end - start + 1; } for (int i = start; i <= end; i++) { printf("%d ", nums[i]); } return 0; }该程序从输入数组中找出最长的严格递增子串,并将其输出。程序的核心思路是使用两个指针(start 和 end)来记录当前最长递增子串的起始和结束位置,同时使用 maxLength 变量记录当前最大长度。在遍历过程中,如果发现 nums[i] 比前一个数小,则表示当前递增子串结束,需要更新 start 和 end,并计算当前子串的长度。最后,输出最长递增子串即可。
- User
用C语言编写一段简单代码,题目要求为: 最長嚴格遞增子數列:寫一個程式,自一串整數中找出最長的嚴格遞增子字串,即是從原一串整數中,找到一個子集合;按照原來的順序排列時,是下一個比前一個值大,並且此子集合個數會最大(即排出來的子字串最長)。
- Assistant
以下是用C语言编写的解决方案:
#include <stdio.h> int main() { int nums[] = {-17, 11, 9, 2, 3, 8, 8, 10, -1, 6, 4, 2}; int n = sizeof(nums) / sizeof(nums[0]); int maxLength = 0; int currentLength = 1; int endIndex = 0; for (int i = 1; i < n; i++) { if (nums[i] > nums[i-1]) { currentLength++; } else { if(currentLength > maxLength) { maxLength = currentLength; endIndex = i-1; } currentLength = 1; } } if(currentLength > maxLength) { maxLength = currentLength; endIndex = n-1; } int startIndex = endIndex - maxLength + 1; for (int i = startIndex; i <= endIndex; i++) { printf("%d ", nums[i]); } return 0; }该程序从输入数组中找出最长的严格递增子串,并将其输出。程序的核心思路是使用两个变量 (maxLength 和 currentLength) 来记录当前最大长度和当前递增子串的长度。在遍历过程中,如果发现 nums[i] 比前一个数大,则将 currentLength 加1,否则更新 maxLength 和 endIndex,并重新开始计算 currentLength。最后,根据 startIndex 和 endIndex 输出最长递增子串。