leetcode -- 面试题59 - II、409

面试题59 - II. 队列的最大值

Problem Description

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。

若队列为空,pop_front 和 max_value 需要返回 -1

示例 1:

输入:
[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]

示例 2:

输入:
[“MaxQueue”,“pop_front”,“max_value”]
[[],[],[]]
输出: [null,-1,-1]

限制:

  • 1 <= push_back,pop_front,max_value的总操作数 <= 10000
  • 1 <= value <= 10^5

Solution Method

下面求max的时间复杂度并不是O(1),而是O(n)。我记得之前做过一个这样的题目,max是O(1),但是忘了。。。。

typedef struct {
    int front;
    int rear;
    int maxValue;
    int * point;
    int len;
} MaxQueue;


MaxQueue* maxQueueCreate()
{
    MaxQueue * mq = (MaxQueue *) malloc (sizeof(MaxQueue));
    mq->point = (int *) malloc (sizeof(int) * 100010);
    mq->len = 100010;
    mq->front = mq->rear = 0;       // 默认指向第零个元素
    mq->maxValue = 0x80000000;
    return mq;
}

int maxQueueMax_value(MaxQueue* obj) 
{
    if (obj->front == obj->rear)		// 是否为空
        return -1;
    obj->maxValue = obj->point[obj->front];
    for (int i = obj->front; i < obj->rear; i ++)
    {
        if (obj->point[i] > obj->maxValue)
            obj->maxValue = obj->point[i];
    }
    return obj->maxValue;
}

void maxQueuePush_back(MaxQueue* obj, int value) 
{
    if ((obj->rear + 1) % obj->len == obj->front)    // 队列满了
        return;
    obj->point[obj->rear] = value;
    obj->rear = (obj->rear + 1) % obj->len;
    printf("rear = %d\n", obj->rear);
}

int maxQueuePop_front(MaxQueue* obj) 
{
    if (obj->front == obj->rear)
        return -1;
    return obj->point[obj->front++];
}

void maxQueueFree(MaxQueue* obj) 
{
    free(obj->point);
    obj->point = NULL;
}

在这里插入图片描述

409.最长回文串

Problem Description

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example “Aa” is not considered a palindrome here.

Note:

  • Assume the length of given string will not exceed 1,010.

Example:

Input:
“abccccdd”
Output:
7

Explanation:

  • One longest palindrome that can be built is “dccaccd”, whose length is 7.

Solution Method

基本思路就是看出现字母个数为双数的个数,再看有没有字母个数为单数的个数出现。

int longestPalindrome(char * s)
{
    int hash[58], count = 0, flag = 0;
    memset(hash, 0, sizeof(int) * 58);
    for (int i = 0; i < strlen(s); i ++)
    {
        hash[s[i] - 'A'] ++;
    }
    for (int i = 0; i < 58; i ++)
    {
        if (hash[i] % 2 == 1)
            flag = 1;
        if (hash[i] != 0)
        {
            count += hash[i] / 2;
        }
    }
    return 2 * count + flag;
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章