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;
}

在這裏插入圖片描述

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