leetcode刷题C语法demo
2019-10-31 本文已影响0人
加97
- 以下实例代码展示了在leetcode解题是必要的基本语法知识,主要涉及数组,二维数组与指针,排序,查找等。
/*
* Copyright (c) Orange Technologies Co., Ltd. 2012-2018. All rights reserved.
* Description: 项目 test 的源文件 leetCode刷题 C语言库函数使用demo, 常见语法使用demo
* Author: *****
* Create: 2019-10-31
*/
#include <stdio.h>
#include <stdlib.h>
// 可选的头文件引用
#include "securec.h"
// 快排比较函数
int compare(const void *a, const void*b)
{
return *(int *)a - *(int *)b;
}
void printArray(int **a, int m, int n)
{
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", a[i][j]);
if (j == n - 1) {
printf("\n");
}
}
}
}
// 传参方式不同时
void printArrayAlt(int **a, int m, int n)
{
int (*b)[n] = a;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", b[i][j]);
if (j == n - 1) {
printf("\n");
}
}
}
}
int main()
{
// 字符串数组
char a[][4] = {"eat", "tea", "tan", "ate", "nat", "bat"};
for (int i = 0; i < 6; i++) {
printf("%s\n", &a[i][0]);
}
// 二维数组传参,动态申请
int array[3][4] = {
{1, 2, 3 ,4},
{4, 3, 2, 1},
{7, 8 ,9, 0}
};
int *pArray[3] = {&array[0][0], &array[1][0], &array[2][0]};
printArray(pArray, 3, 4);
// 不推荐
// printArrayAlt(array, 3, 4);
// 动态申请一维数组以及二维数组以及初始化
int const m = 3, n = 4;
int *p = (int *) malloc(sizeof(int) * n);
// 重要:初始化内存的长度要考虑数组中的元素类型
memset(p, 0, n * sizeof(int));
for (int i = 0; i < n; i++) {
printf("%d ", p[i]);
}
printf("\n");
int (*dArray) [n] = (int (*)[n]) malloc(sizeof(int) * m * n);
for (int i = 0; i < m; i++) {
memset(&dArray[i][0], 0, n * sizeof(int));
}
printArrayAlt(dArray, m, n);
// 快排
int count = 5;
int qsortArray[5] = {3, 4, 5, 1, 2};
qsort(qsortArray, count, sizeof(int), compare);
printf("qsort result:\n");
for (size_t i = 0; i < 5; i++) {
printf("%d ", qsortArray[i]);
}
printf("\n");
// 二分查找
int key = 5;
int *result = bsearch(&key, qsortArray, count, sizeof(int), compare);
if (result != NULL) {
printf("%d exist in the array\n", *result);
}
// 释放内存
if (dArray != NULL) {
free(dArray);
}
if (p != NULL) {
free(p);
}
return 0;
}