leetcode题解日练--2016.6.26

How time flies!
编程日记,尽量保证每天至少3道leetcode题,仅此记录学习的一些题目答案与思路,尽量用多种思路来分析解决问题,不足之处还望指出。标红题为之后还需要再看的题目。

今日题目:1、判断数组是否含有重复元素II(长为K区间);2、合并两个排序数组;3、删除链表的倒数第N个节点;4、模式匹配字符串

219. Contains Duplicate II | Difficulty: Easy

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
题意:找到数组中是否存在一个整数k使得在k范围内存在两个相等的数。
思路:
1、最初是用的暴力破解的方法,结果测试用例中有一组0-29999,k=15000的数据,直接超时了。那么应该怎么做呢?很显然我们需要一个大小为大小为k的窗口,然后每次滑动这个窗口,查找新元素是否存在,如果存在则说明找到了,如果不存在则说明不存在,将新元素加入。还有需要注意的是如果集合元素满了k之后就需要开始移除元素了。
代码:
C++

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_set<int> s;
        if (k<0) return false;
        if (k>nums.size())    k = nums.size()-1;
        for(int i=0;iif(i>k) s.erase(nums[i-k-1]);
            if(s.find(nums[i])!=s.end())    return true;
            s.insert(nums[i]);
        }
        return false;
    }
};

结果:32ms

88. Merge Sorted Array | Difficulty: Easy

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

题意:将两个排序好的数组合并到nums1中去。
思路:
1、既然之前已经是排序好的数组,那么很显然的思路就是先从后到前,逐个比较两个数组中的元素,大的先加
c++

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m-1;
        int j = n-1;
        int k = m+n-1;
        //当nums1和nums2中都有元素的时候,从它们的最后位置开始进行比较,大的放入nums1
        while(i>=0&&j>=0)
        {
            if(nums1[i]>nums2[j])
                nums1[k--] = nums1[i--];
            else
                nums1[k--] = nums2[j--];
        }
        //其实这个判断可以省略的,应该我们最终是需要将所有元素放在nums1中,那么如果nums2先遍历完,就不需要再操作nums1了,反之如果nums1先遍历完,还需要将nums2中的元素加入到nums1中,这里保留i==-1只是为了逻辑上好理解一点
        if(i==-1)
        {
            for(j;j>=0;)
                nums1[k--] = nums2[j--];
        }

    }
};

结果:4ms

19. Remove Nth Node From End of List | Difficulty: Easy

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.

题意:给定一个链表,删除第n个节点
思路:可以利用二级指针来完成这个任务,指针的作用是指向被删除的节点,然后将它的前后连接起来。那么怎么使得这个二级指针能够指向我们希望的节点呢?倒数第n个节点就需要我们在正常的节点走到最后一个节点的时候,二级指针走到倒数第n个节点,也就是正常的节点要先走n-1步。
代码:
C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode **pNode1 = &head,*pNode2 = head;
        for(int i=0;i1;i++)
            pNode2 = pNode2->next;
        while(pNode2->next!=NULL)
        {
            pNode1 = &((*pNode1)->next);
            pNode2 = pNode2->next;
        }
        *pNode1 = (*pNode1)->next;
        return head;
    }
};

结果:4ms
第二次刷代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head==NULL )  return head;
        ListNode *newHead = new ListNode(INT_MIN);
        newHead->next=head;
        ListNode *fast =head,*slow=newHead;
        while(fast->next && --n)
        {
            fast = fast->next;
        }
        while(fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode*tmp = slow->next;
        slow->next = tmp->next;
        delete(tmp);
        return newHead->next;
    }
};

结果:4ms

290. Word Pattern | Difficulty: Easy

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
题意:给定一个模式,判断字符串是否符合模式
思路:
1、首先创建一个python字典,遍历每个模式,如果这个模式没在字典中,做一次判断这个模式对应的值是否出现再其他模式,如果出现就返回False,如果没出现将这个模式作为key,str作为value加入字典,如果之前这个模式出现过但是值和当前值不一样,这种情况也是一样返回False,到最后还没False就是True。
这里用python来做是因为一下忘记了C++的一些字符串处理方法了。
代码:
python

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        dic = {}
        str_split = str.split(' ')
        if len(str_split)!= len(pattern):
            return False
        for i in range(len(str_split)):
            if pattern[i] not in dic.keys():
                if str_split[i] not in dic.values():
                    dic[pattern[i]] = str_split[i]
                else:
                    return False
            else:
                if dic[pattern[i]]!=str_split[i]:
                    return False
        return True

结果:52ms
2、参考了
https://leetcode.com/discuss/62476/short-c-read-words-on-the-fly
遇到分隔符的字符串读入字符,python可用split、C++可用istringstream

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        //p2i记录的是每一个pattern的index,w2i记录的是每一个word的index
        //每次输入一个word,看其与对应的pattern的index是否相等,如果不等,就错误了,如果相等就同时更新p2i和w2i
        unordered_map<char,int> p2i;
        unordered_map<string,int> w2i;
        int i=0,n = pattern.length();
        istringstream in(str);
        for(string word;in >> word;i++)
        {
            if(i==n|| p2i[pattern[i]]!=w2i[word])   return false;
            p2i[pattern[i]] = w2i[word] = i + 1;
        }
        return i==n;
    }
};

结果:3ms

你可能感兴趣的:(leetcode,leetcode,编程,日记)