leetcode -- 面试题10.01、387

面试题 10.01. Sorted Merge LCCI

Problem Description

You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.

Initially the number of elements in A and B are m and n respectively.

Example:

Input:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6], n = 3
Output: [1,2,2,3,5,6]

Solution Method

从后往前

void merge(int* A, int ASize, int m, int* B, int BSize, int n)
{
    int count = 0;
    int i = m - 1, j = n - 1;

    for (; i >= 0 && j >= 0;)
    {
        count ++;
        if (A[i] >= B[j])
        {
            A[ASize - count] = A[i];
            i --;
        }
        else if (A[i] < B[j])
        {
            A[ASize - count] = B[j];
            j --;
        }
    }
    while (i >= 0)
    {
        count ++;
        A[ASize - count] = A[i];
        i --;
    }
    while (j >= 0)
    {
        count ++;
        A[ASize - count] = B[j];
        j --;
    }
}

在这里插入图片描述

387.387. First Unique Character in a String

Problem Description

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = “leetcode”
返回 0.

s = “loveleetcode”,
返回 2.

Solution Method

看着这个题目我也是服了,我以为他说的不重复是指前面出现的,谁知道是整个字符串。

int firstUniqChar(char * s)
{
    int hash[26];
    memset(hash, 0, sizeof(int) * 26);
    for (int i = 0; i < strlen(s); i ++)
    {
        hash[s[i] - 'a'] ++;
    }
    for (int i = 0; i < strlen(s); i ++)
    {
        if (hash[s[i] - 'a'] == 1)
            return i;
    }
    return -1;
}

在这里插入图片描述
我也是服了,时间空间复杂度都是O(n),怎么结果这么差,和题解方法一样的啊。

发布了184 篇原创文章 · 获赞 253 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/williamgavin/article/details/104626715