题目1:判断数组是否有序(升序或者降序)
思路和代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{int a = 0;scanf("%d", &a);int arr[50];int flag1 = 0;//是降序int flag2 = 0;//是升序for (int i = 0; i < a; i++){scanf("%d", &arr[i]);if (i > 0){if (arr[i] >= arr[i - 1])//如果存在降序{flag1 = 1;//降序赋值为1}if (arr[i] < arr[i - 1])//如果存在升序{flag2 = 1;//升序赋值为1}}}if (flag1 + flag2 == 1)//满足升序或者降序其中一个就是有序数组{printf("sorted\n");}else//反之不是{printf("unsorted\n");}
}
题目2:去除数组中重复的数字
思路和代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{int a = 0;scanf("%d", &a);int arr[1000];//读取for (int i = 0; i < a; i++){scanf("%d", &arr[i]);}//去重for (int i = 0; i < a; i++){int j = 0;for (j = i + 1; j < a; j++)//从下一个元素开始找{if (arr[i] == arr[j])//重复{//去重,后面元素往前覆盖int k = 0;for (k = j; k < a - 1; k++){arr[k] = arr[k + 1];//因为最大到a,所以k+1<a,k<a-1}a--;//数组个数减少一个j--;下标回退,重新判断后面有没有重复的}}}for (int i = 0; i < a; i++){printf("%d ", arr[i]);}return 0;}
题目3:合并,排序两个有序数组,并打印
思路和代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{int n = 0;int m = 0;//创建两个数组int arr1[100] = { 0 };int arr2[100] = { 0 };//传入两个数组的元素个数scanf("%d %d", &n, &m);int i = 0;//输入数组1for (i = 0; i < n; i++){scanf("%d", &arr1[i]);}//输入数组2for (i = 0; i < m; i++){scanf("%d", &arr2[i]);}//int j = 0;i = 0;//合并while (i < n && j < m){if (arr1[i] < arr2[j])//哪个数组元素小先打印谁{printf("%d ", arr1[i]);i++;}else{printf("%d ", arr2[j]);j++;}}if (i == n)//相等都打印一次{for (; j < m; j++){printf("%d ", arr2[j]);}}else{for (; i < n; i++){printf("%d ", arr1[i]);}}return 0;
}