力扣刷题1

73 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情


错误的集合

在这里插入图片描述

解题思路

建一个有序的集合,数据从小到大1~n。然后依次遍历原集合,原集合里面的数据出现一次就把有序集合中的该数据制成0,当遍历的时候有序集合出现为0的情况,就找到了重复的一个数值,当遍历完的时候,有序集合中非0的就是缺少的数值。 ==时间复杂度O(n),空间复杂度O(n)==

代码

int* findErrorNums(int* nums, int numsSize, int* returnSize){
    *returnSize=2;
    int* duibi=(int*)malloc(sizeof(int)*numsSize);
    int* ret=(int*)malloc((*returnSize)*sizeof(int));
    int i=0;
    for(i=0;i<numsSize;i++)
    duibi[i]=i+1;
    for(i=0;i<numsSize;i++)
    {
        if(duibi[nums[i]-1]  ==0)
        ret[0]=nums[i];
        else
        duibi[nums[i]-1]=0;
    }
    for(i=0;i<numsSize;i++)
    if(duibi[i]!=0)
    ret[1]=duibi[i];
    free(duibi);
    return ret;
}

有效的括号

在这里插入图片描述

解题思路

这可以看出来是对栈的考察,栈中先进左括号,发现右括号的时候出栈,直到栈中的左括号全部匹配。

代码

typedef char StackTypeDate;
typedef struct Stack
{
    StackTypeDate* arr;
    int top;
    int capacity;
}Stack;

void InitStack(Stack* ps)
{
    assert(ps);
    ps->arr=NULL;
    ps->top=ps->capacity=0;
}
void StackDestroy(Stack* ps)
{
    assert(ps);
    free(ps->arr);
    ps->arr=NULL;
    ps->top=ps->capacity=0;
}
void StackPush(Stack* ps,StackTypeDate x)
{
    assert(ps);
    if(ps->top==ps->capacity)
    {
        int NewCapa=ps->capacity==0?4:ps->capacity*2;
        ps->arr=(StackTypeDate*)realloc(ps->arr,sizeof(StackTypeDate)*NewCapa);
        ps->capacity=NewCapa;
    }
    ps->arr[ps->top]=x;
    ps->top++;
}
bool StackEmpty(Stack* ps)
{
    assert(ps);
    return ps->top==0;
}
void StackPop(Stack* ps)
{
    assert(ps);
    assert(!StackEmpty(ps));
    ps->top--;
}
StackTypeDate StackTop(Stack* ps)
{
    assert(ps);
    assert(!StackEmpty(ps));
    return ps->arr[ps->top-1];
}
//上面代码是创建栈
//在返回前要记得销毁栈
bool isValid(char * s){
    Stack p;
    InitStack(&p);
    while(*s)
    {
        if(*s=='('||*s=='['||*s=='{')
        {
            StackPush(&p,*s);
            s++;
        }
        else
        {
            //栈本身没有数据
            if(StackEmpty(&p))
            {
                StackDestroy(&p);
                return false;
            }    
            //从栈顶取数据
            StackTypeDate ch=StackTop(&p);
            if((*s==')'&&ch=='(')||(*s==']'&&ch=='[')||(*s=='}'&&ch=='{'))
            {
                s++;
                StackPop(&p);
            }
            else
            {
                StackDestroy(&p);
                return false;
            }         
        }
    }
    bool empty=StackEmpty(&p);
    StackDestroy(&p);
    return empty;
}