文章目錄
面試題 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),怎麼結果這麼差,和題解方法一樣的啊。