leetcode:1-5题代码整理

以下是这段时间抽时间刷的前5题,都是自己想的解法,或许不是最优解,只是整理下,方便日后优化提升

1. Two Sum:

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        dict = {}
        for i in xrange(len(num)):
            if dict.get(target-num[i], None) == None:
                dict[num[i]] = i
            else:
                return (dict[target-num[i]] , i )

2. Add Two Numbers:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        more=0
        l3=ListNode(0)

        l3.val=l1.val+l2.val+more
        if l3.val>=10:
            more=1
        else:
            more=0
        l3.val=l3.val%10
        l1_temp=l3
        l1=l1.next
        l2=l2.next

        while(l1 and l2):
            temp=ListNode(0)
            temp.val=l1.val+l2.val+more
            if temp.val>=10:
                more=1
            else:
                more=0
            temp.val=temp.val%10

            l1_temp.next=temp
            l1_temp=temp
            l1=l1.next
            l2=l2.next

        if((l1 is None )and( l2 is None)):
            if more==1:
                temp=ListNode(0)
                temp.val=1
                l1_temp.next=temp
            return l3

        elif(l1 and ( l2 is None)):
            while(l1):
                temp=ListNode(0)
                temp.val=more+l1.val
                if temp.val>=10:
                    more=1
                else:
                    more=0
                temp.val=temp.val%10
                l1_temp.next=temp
                l1_temp=temp
                l1=l1.next
            if more==1:
                temp=ListNode(0)
                temp.val=1
                l1_temp.next=temp
            return l3

        elif(l2 and ( l1 is None)):
            while(l2):
                temp=ListNode(0)
                temp.val=more+l2.val
                if temp.val>=10:
                    more=1
                else:
                    more=0
                temp.val=temp.val%10
                l1_temp.next=temp
                l1_temp=temp
                l2=l2.next
            if more==1:
                temp=ListNode(0)
                temp.val=1
                l1_temp.next=temp
            return l3

3. Longest Substring Without Repeating Characters:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        new_str = ‘‘
        max = 0
        for ch in s:
            if not ch in new_str:
                new_str += ch
            else:
                max = len(new_str) if len(new_str) > max else max
                idx = new_str.find(ch)
                new_str = new_str[idx+1:] + ch
        max = len(new_str) if len(new_str) > max else max
        return max

4. Median of Two Sorted Arrays:

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        end1=len(nums1)-1
        end2=len(nums2)-1
        if len(nums1)==0:
            num=len(nums2)
            if num%2:     #num是一个奇数
                return float(nums2[num/2])
            else:
                median=num/2
                return (float(nums2[median-1])+nums2[median])/2

        elif len(nums2)==0:
            num=len(nums1)
            if num%2:     #num是一个奇数
                median=num/2
                return float(nums1[median])
            else:
                median=num/2
                return (float(nums1[median-1])+nums1[median])/2

        elif nums1[end1]<nums2[0]:
            nums1.extend(nums2)
            num=len(nums1)
            if num%2:     #num是一个奇数
                median=num/2
                return float(nums1[median])
            else:
                median=num/2
                return (float(nums1[median-1])+nums1[median])/2

        elif nums1[0]>nums2[end2]:
            nums2.extend(nums1)
            num=len(nums2)
            if num%2:     #num是一个奇数
                return float(nums2[num/2])
            else:
                median=num/2
                return (float(nums2[median-1])+nums2[median])/2

        else:
            i=0
            j=0
            new=[]
            while i<len(nums1) and j<len(nums2):
                if nums1[i]<nums2[j]:
                    new.append(nums1[i])
                    i=i+1
                elif nums1[i]==nums2[j]:
                    new.append(nums1[i])
                    new.append(nums1[i])
                    i=i+1
                    j=j+1
                else:
                    new.append(nums2[j])
                    j=j+1
            while i<len(nums1):
                new.append(nums1[i])
                i=i+1
            while j<len(nums2):
                new.append(nums2[j])
                j=j+1
            num=len(new)
            if num%2:     #num是一个奇数
                return float(new[num/2])
            else:
                median=num/2
                return (float(new[median-1])+new[median])/2

5. Longest Palindromic Substring:

class Solution(object):

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s)==1:
            return s
        elif len(s)==2 and s[0]==s[1]:
            return s
        else:
            s_fin1=""
            s_fin2=""

            index_l=0
            index_r=1
            max_length=0
            left=-1
            right=-1
            flag=0
            while index_r<len(s):
                i=0
                length=0
                while index_l-i>=0 and index_r+i<len(s) and s[index_l-i]==s[index_r+i]:
                    i=i+1
                    length=length+2
                if length>max_length:
                    max_length=length
                    left=index_l
                    right=index_r
                index_l=index_l+1
                index_r=index_r+1
            if max_length:
                begin=left-max_length/2+1
                end=right+max_length/2
                flag=2
                s_fin1=s[begin:end]

            index=1
            max_length=1
            center=-1
            flag=0
            while index<(len(s)-1):
                i=1
                length=1
                while index-i>=0 and index+i<len(s) and s[index-i]==s[index+i]:
                    i=i+1
                    length=length+2
                if length>max_length:
                    max_length=length
                    center=index
                index=index+1
            if max_length>1:
                begin=center-(max_length-1)/2
                end=center+(max_length-1)/2+1
                flag=1
                s_fin2=s[begin:end]

            if len(s_fin1)>len(s_fin2):
                return s_fin1
            else:
                return s_fin2
时间: 2024-10-11 03:38:06

leetcode:1-5题代码整理的相关文章

LeetCode 第 73 题 (Set Matrix Zeroes)

LeetCode 第 73 题 (Set Matrix Zeroes) Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably a bad idea. A simple impro

leetcode中第一题twosum问题解答算法的可行性证明

leetcode中第一题twosum问题解答算法的可行性证明 一.引入 关于leetcode中第一题twosum问题,网上已有不少高人做出过解答,并提出了切实可行的算法实现.我在解答该题时参考了博客http://www.zixue7.com/article-9576-1.html的解答.为让读者更直观地阅读和理解本文,先简要摘录以上博客的内容如下: 题目还原 Two Sum Given an array of integers, find two numbers such that they a

LeetCode 第三题,Longest Substring Without Repeating Characters

题目: Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest s

leetcode第9题-Palindrom Number

这是leetcode的第九题,相对来说比较简单,目的很简单,就是判断一个int型的数是不是回文数.但是有几点需要考虑: 负数应该没有回文数,要加判断!要注意额外的空间申请问题.判断是否是回文数势必要对一个数进行反转,反转的时候就要考虑溢出的问题.实现的代码如下: #include<stdio.h> bool isPalindrom(int x) { if(x<0) return false; else { int tmp=x; int sum=0; while(tmp) { sum=su

LeetCode 第 19 题 (Remove Nth Node From End of List)

LeetCode 第 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 li

LeetCode 第 342 题(Power of Four)

LeetCode 第 342 题(Power of Four) Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. Follow up: Could you solve it without loops/recursion? 题目很简单,

LeetCode第四题,Add Two Numbers

题目原文: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6

LeetCode 第 342 题(Power of Four)

LeetCode 第 342 题(Power of Four) Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Given num = 16, return true. Given num = 5, return false. Follow up: Could you solve it without loops/recursion? 题目非常eas

LeetCode 第 263 题 (Ugly Number)

LeetCode 第 263 题 (Ugly Number) Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another pr