1.两数之和
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, j;
for(i = 0; i<numsSize; ++i){
for(j = i+1; j<numsSize; ++j){
if(nums[i] + nums[j] == target){ //满足条件
int *x = malloc(sizeof(int)*2); //动态数组指针,可随时分配空间
x[0] = i;
x[1] = j;
*returnSize = 2;
return x;
}
}
}
*returnSize = 0;
return NULL;
}
int *x = malloc(sizeof(int)*2) //分配数组指针,可以随时分配空间
思路:
- 设置两个指针,分别遍历链表
- 当满足nums[ i ] + nums[ j ] = target 时满足条件
- 设置内存为两个数据元素,8个字节的动态数组保存nums[ i ] 和 nums[ j ]
- 最后返回数组x
20.有效的括号
bool isValid(char * s){
int n = strlen(s); //strlen计算字符串长度,并返回,赋值给n
if (n % 2 == 1) { //如果括号为单数,则必定不匹配
return false;
}
int stk[n + 1], top = 0; //定义一个数组栈,多加一个存放栈顶指针
for (int i = 0; i < n; i++) { //遍历数组栈
char ch = s[i]; //存放括号
if(s[i] == '}' ) {
ch = '{';
}else if(s[i] == ']'){ //开始出现右括号时,匹配去除左右括号
ch = '['; //把左括号赋值给ch
} else if (s[i] == ')'){
ch = '(';
}else{
ch = 0;
}
if (ch != 0) { //若ch不为空,也就是还有右括号没有消除
if (top == 0 || stk[top - 1] != ch) {
return false; //当栈为空或栈顶的下一个元素不与栈顶括号匹配时
} //返回失败
top--;
} else { //这是还没有左括号加入栈时,将左括号入栈
stk[top] = s[i];
top++;
}
}
return top == 0; //做判断