int search(int list[], int n, int x) { int flag = 0; for(int i = 0; i < n; i++) { if(list[i] == x) { flag = 1; return i; } } if(flag == 0) return -1; }
void ArrayShift(int a[], int n, int m) { int arr[m>n?m:n]; if(m>n) m-=n; for (int i = 0; i < m; i++) { arr[i] = a[n - m + i]; } for (int k = 0; k < n - m; k++) { arr[m + k] = a[k]; } for(int j = 0; j < n; j++) { a[j]=arr[j]; } }
这道题就是leecode中的转轮数组,需要注意的是要考虑右移的长度大于等于数组本身的长度的时候,这时,我们不妨用取余解决,同时除了这种方法我们还有一种方法
我们给定一个数组1 4 9 6 3 5
让它右移两位,首先将这个数组拆分一下1 4 9 6 3 5
让第一部分反转4 1
让第二部分反转5 3 6 9
合一起后反转9 6 3 5 1 4这个就是我们最后的答案
int FindArrayMax( int a[], int n ) { int max = 0; for(int i = 0; i < n; i++) { if(a[i] > max) max = a[i]; } return max; }
int FindArrayMax( int a[], int n ) { int max = a[0]; for(int i = 0; i < n; i++) { if(a[i] > max) max = a[i]; } return max; } int main() { int n = 0; scanf("%d",&n); int a[n]; for(int i = 0; i < n; i++) { scanf("%d",&a[i]); } int max = FindArrayMax(a,n); int j = 0; for(j = 0; j < n; j++) { if(a[j] == max) break; } printf("%d %d",max,j); }
int main() { int n = 0, flag = 0; scanf("%d",&n); int a[n]; for(int i = 0; i < n; i++) { scanf("%d",&a[i]); } for(int i = n - 1; i >= 0; i--) { if(flag == 0) { printf("%d",a[i]); flag = 1; } else printf(" %d",a[i]); } }
int cmp_arr(const void* p1, const void* p2) { return *(int*)p2 - *(int*)p1; } int main() { int n = 0, flag = 0; scanf("%d",&n); int a[n]; for(int i = 0; i < n; i++) { scanf("%d",&a[i]); } qsort(a,n,sizeof(a[0]),cmp_arr); for(int i = 0; i < n; i++) { if(flag == 0) { printf("%d",a[i]); flag = 1; } else printf(" %d",a[i]); } }
int main() { int m, n, a[100][100]; scanf("%d%d", &m, &n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { scanf("%d", &a[i][j]); } } for (int i = 0; i < m; i++) { int sum = 0; for (int j = 0; j < n; j++) { sum += a[i][j]; } printf("%d\n", sum); } }
int cmp_arr(const void* p1, const void* p2) { return *(int*)p1 - *(int*)p2; } int main() { int n, a[100], b[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); b[i] = a[i]; } qsort(b, n, sizeof(b[0]), cmp_arr); int max = b[n - 1], min = b[0]; for (int i = 0; i < n; i++) { int tmp = 0; if (a[i] == max) { tmp = a[i]; a[i] = a[n - 1]; a[n - 1] = tmp; } if (a[i] == min) { tmp = a[i]; a[i] = a[0]; a[0] = tmp; } } for (int i = 0; i < n; i++) { printf("%d ", a[i]); } }