Leetcode--easy系列2

#14 Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

这个题求多个字符串的公共前缀,除了要考虑串空外,如果存在公共前缀,那么必定也是第一个串的前缀。

所以可以以第一个串为基准,比较其他串的前缀是否与第一个串相同。

char* longestCommonPrefix(char** strs, int strsSize) {
    char *s0,*si;
    int index;//指示比较位置
    if (strsSize <= 0 || strs == NULL) return strs;
    if (strsSize == 1) return strs[0];
    s0 = strs[0];//以第一个字符串为基准
    for (int i = 1; i < strsSize; ++i)
    {
        si = strs[i];
        index = 0;//每个字符串从0位置开始比较
        while (true)
        {
            if (s0[index] != si[index] || s0[index] == NULL || si[index] == NULL)
            {
                s0[index] = '\0';//对于不相等的位置,必定不是公共前缀
                break;
            }
            index++;
        }
    }
    return strs[0];
}

#19 Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Try to do this in one pass.

//0ms
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    int len=0,j=0;
	struct ListNode *p,*q;
	p = head;//指向第一个元素 没有头结点
	//求链表长度
	while(p!=NULL)
	{
		p = p->next;
		len++;
	}
	//边界条件
	if(len-n<0)
		return NULL;
    if(len==1 &&n==1)
        return NULL;
	p = head;//指向第一个元素
	q=p;
	//删除的元素是第一个位置,不存在q所有先讨论
	if(n==len)
	{
		p =head->next;
		return p;
	}
	//一般条件---待删除元素位于第len-n+1个位置,倒数第n个位置
	for(j=1;j<=len-n;j++)
	{
		q = p;//q指向待删除元素前一个元素第len-n个元素
		p = p->next;//p指向待删除元素---第len-n+1个元素
	}
	q->next = p->next;
	return head;
}

在leetcode discuss里面又看到另外一种写法,一次遍历得到待删除节点位置

struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
	struct ListNode* front = head;
	struct ListNode* behind = head;
	//front后移len长度,behind后移len-n长度,behind->next即为待删除节点
	while (front != NULL)
	{
		front = front->next;
		if (n-- < 0)
			behind = behind->next;
	}
	if (n == 0)//len==n
		head = head->next;
	else
		behind->next = behind->next->next;
	return head;
}

#20 Valid Parentheses

Given a string containing just the characters ‘(‘‘)‘‘{‘‘}‘‘[‘ and ‘]‘,
determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are
not.

括号匹配,首先想到栈。

bool isValid(char* s) {
    int i,top,len;
	char *a;
	char ch;
	len = strlen(s);
	a = (char *)malloc(sizeof(char)*len);
	top =-1;
	for(i=0;i<len;i++)
	{
		ch = s[i];
		if(ch=='{'||ch=='('||ch=='[')
			a[++top] = ch;
		if(ch==']'||ch==')'||ch=='}')
		{
			if(top==-1)
				return false;
			else if(ch==']'&& a[top]=='[')
				top--;
			else if(ch=='}'&& a[top]=='{')
				top--;
			else if(ch==')'&& a[top]=='(')
				top--;
			else
			    return false;
		}
	}
	if(top==-1)
	    return true;
	else
	    return false;
}

#21 Merge Two Sorted Lists

Merge
two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

合并两个有序链表---首先想到了归并排序最后的合并两个有序数组,写法完全类似。查了以下discuss 发现一种递归的写法。

/**4ms
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
	struct ListNode *p,*head;
	head = p;
	if(l1==NULL)
	    return l2;
	if(l2==NULL)
	    return l1;
	while(l1&&l2)
	{
		if(l1->val <= l2->val)
		{
			p->next = l1;
			l1 = l1->next;
		}
		else
		{
			p->next = l2;
			l2 = l2->next;
		}
		p = p->next;
	}
	if(l1)
		p->next = l1;
	if(l2)
		p->next = l2;
	return head->next;
}
/**4ms
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
	struct ListNode* l3;
	if(l1==NULL)
		return l2;
	if(l2==NULL)
		return l1;
	if(l1->val < l2->val)
	{
		l3 = l1;
		l3->next = mergeTwoLists(l1->next,l2);
	}
	else
	{
		l3 = l2;
		l3->next = mergeTwoLists(l1,l2->next);
	}
	return l3;
}
时间: 2024-10-17 06:00:09

Leetcode--easy系列2的相关文章

Leetcode permutation 系列

关于permutation的讲解,请参见http://blog.csdn.net/xuqingict/article/details/24840183 下列题目的讲解均是基于上面的文章: 题1: Next Permutation Total Accepted: 8066 Total Submissions: 32493My Submissions Implement next permutation, which rearranges numbers into the lexicographic

【Leetcode长征系列】Letter Combinations of a Phone Number

原题: Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae"

【Leetcode长征系列】Merge k Sorted Lists

原题: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:两条两条地合并.时间复杂度为O(n),n为所有链表节点和. 代码: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) :

[LeetCode蠕动系列]Sort List

这题前一阵子就看到了,一直没时间做,昨晚睡前想了想,要求n*log(n)以内的时间复杂度,第一时间想到的就是归并.快排和希尔排序(注:希尔排序时间为O(n^1.3),在数据量大于2的情况下小于n*log(n)),个人以为,链表的特性更适合归并,所以采用归并排序,实现的merge代码如下: public static ListNode merge(ListNode rhead, ListNode lhead) { ListNode head = null; if (rhead.val <= lhe

HDU 2045不easy系列之三LELE的RPG难题(趋向于DP的递推)

不easy系列之(3)-- LELE的RPG难题 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 30222 Accepted Submission(s): 12144 Problem Description 人称"AC女之杀手"的超级偶像LELE近期忽然玩起了深沉,这可急坏了众多"Cole"(LELE的粉丝,即

【Leetcode长征系列】Construct Binary Tree from Inorder and Postorder Traversal

原题: Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路:和上一题一样,后续我们可以通过最后一个值得到根的值,同样可以通过定位根的值得到左右子树的子集,递归求解即可. 代码: /** * Definition for binary tree * struct Tre

【Leetcode长征系列】Single Number II

原题: Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 思路: 用一个32位的数组存每一位bit值之后.得到答案后每一位除

【Leetcode长征系列】Pow(x, n)

原题: Implement pow(x, n). 思路:递归计算pow. class Solution { public: double pow(double x, int n) { long long int mid = n/2; int d = n%2; if(n==0) return 1; if(n==1) return x; if(d==1) return pow(x, (n/2)+1) * pow(x, n/2); else return pow(x, n/2) * pow(x, n/

【Leetcode长征系列】Sqrt(x)

原题: Implement int sqrt(int x). Compute and return the square root of x. ==============================以下为引用==================================== 牛顿迭代法 为了方便理解,就先以本题为例: 计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示. 首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交

【Leetcode长征系列】Balanced Binary Tree

原题: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1. 思路:递归判断左右子树是否为BST. 代码: /** * Def