21. 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
一次AC,13分钟写完,中途接了一次中国联通推广电话。思路简单、
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
struct ListNode *h, *t; //head, tail
struct ListNode *q = l1, *p = l2;
if(q->val > p->val)
{
h = t = p;
p = p->next;
}else
{
h = t = q;
q = q->next;
}
while(q != NULL && p != NULL)
{
if(q->val > p->val)
{
t->next = p;
p = p->next;
}else
{
t->next = q;
q = q->next;
}
t = t->next;
}
while(q != NULL)
{
t->next = q;
q = q->next;
t = t->next;
}
while(p != NULL)
{
t->next = p;
p = p->next;
t = t->next;
}
return h;
}
26. 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
7分钟半写完,处理了一次输入空数组的边界条件。
int removeDuplicates(int* nums, int numsSize){
if(numsSize == 0) return 0;
int newArrayindex = 1;
for(int i = 1; i < numsSize; i++)
{
if(nums[i] != nums[i - 1])
nums[newArrayindex++] = nums[i];
}
return newArrayindex;
}
27. 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
2分半写完。有了26的思路,很简单。
int removeElement(int* nums, int numsSize, int val){
if(numsSize == 0) return 0;
int newArrayindex = 0;
for(int i = 0; i < numsSize; i++)
{
if(nums[i] != val)
nums[newArrayindex++] = nums[i];
}
return newArrayindex;
}
28. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
这是一个经典的字符串匹配问题。这里我没有选用KMP,而是使用了暴力搜索方法。6分半写完。
int strStr(char * haystack, char * needle){
if(haystack == NULL || needle == NULL) return -1;
if(needle[0] == '\0') return 0;
int lenh = strlen(haystack), lenn = strlen(needle);
int matchPos = 0;
int i = 0;
while(matchPos + lenn <= lenh)
{
for(i = 0; i < lenn; i++)
{
if(haystack[matchPos + i] != needle[i])
break;
}
if(i == lenn) return matchPos;
matchPos++;
}
return -1;
}
35. 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
三分钟写完。
int searchInsert(int* nums, int numsSize, int target){
int i = 0;
for(i = 0; i < numsSize; i++)
{
if(nums[i] >= target) return i;
}
return numsSize;
}