Leetcode Journey

34 篇文章 0 订阅
16 篇文章 0 订阅

Ransom note

看成了KMP 匹配算法,这边实现了下

void get_next(char *key,int *next)
{ next[0]=0;
int i=0;
int j=-1;
while(i<strlen(key))
{
if(j==-1 || key[i]==key[j])
{
++i;
++j;
next[i]=j;
}
else
{
j=next[j]-1;
}
}
}

bool canConstruct(char* ransomNote, char* magazine)
{
int len=strlen(ransomNote);
int len_mag=strlen(magazine);
int *next=(int *)malloc(sizeof(int)*len);
get_next(ransomNote, next);
for(int i=0;i<len;i++)
{ printf("%d\t",next[i]); }

printf("\n len:%d,len_mag:%d\n",len,len_mag);
int i=0;
int j=0;
while(i<len_mag && j<len)
{
printf("i:%d,j:%d\n",i,j);
if(magazine[i]==ransomNote[j] )
{ i++; j++; }
else
{
if(j==0)
{ i++; }
else
{ j=next[j]; }
}
if(j==len)
{ printf("true\n"); return true; }
}
printf("false\n");
return false;
}

真正的解法:

349 Intersection of Two ArraysHash 表的解法

#define HASHSIZE 1000

/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
int *ret;
int hash[HASHSIZE] = { 0 };

if (!nums1 || !nums2)
return NULL;

*returnSize = 0;
ret = calloc(MAX(nums1Size, nums2Size), sizeof(*nums1));

for (int i = 0; i < nums1Size; ++i)
hash[nums1[i]] = 1;

for (int i = 0; i < nums2Size; ++i)
if (hash[nums2[i]] == 1)
hash[nums2[i]] = 2;

for (int i = 0; i < HASHSIZE; ++i)
if (hash[i] == 2)
ret[(*returnSize)++] = i;

return ret;
}`

169 Majority ElementAll

Solutions
:https://discuss.leetcode.com/topic/17446/6-suggested-solutions-in-c-with-explanations- Hash table:- Moore voting algorithm** introduce to moore voting algorithm**<http://www.cs.utexas.edu/~moore/best
ideas/mjrty/index.html>

int majorityElement(int* nums, int numsSize)
{
int count=0;
int retval=0;
for(int i=0;i<numsSize;i++)
{
if(count==0)
{
retval=nums[i];
count++;
}
else
{
if(retval==nums[i])
{
count++;
}
else
{
count--;
}
}
}
return retval;
}
Bit manipulationint majorityElement(int* nums, int numsSize)
{
int mask=0x00000001;
int retval;
for(int i=0;i<32;i++)
{
int count=0;
for(int j=0;j<numsSize;j++)
{
if(mask&nums[j])
{
count++;
}
}
if(count>numsSize/2)
{
retval|=mask;
}
mask<<=1;
}
}

350. Intersection of Two Arrays IIelegant

solution of python:

def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict1 = dict()
for i in nums1:
if i not in dict1:
dict1[i] = 1
else:
dict1[i] += 1
ret = []
for i in nums2:
if i in dict1 and dict1[i]>0:
ret.append(i)
dict1[i] -= 1
return ret

401. Binary Watch

from collections import defaultdict

class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
minute=defaultdict(lambda:list())
hour=defaultdict(lambda:list())

for i in range(60):
binary='{0:b}'.format(i)
minute[binary.count('1')].append(i)

for j in range(12):
binary='{0:b}'.format(j)
hour[binary.count('1')].append(j)

ret=list()
for i in range(num+1):
for j in hour[i]:
for k in minute[num-i]:
if len(str(k))<2:
ret.append(str(j)+':0'+str(k))
else:
ret.append(str(j)+':'+str(k))

return ret

566. Reshape the Matrix

class Solution(object):

def matrixReshape(self, nums, r, c):
flat = sum(nums, [])
if len(flat) != r * c:
return nums

print [iter(flat)]
print flat

#print *([iter(flat)]*c)
tuples = zip(*([iter(flat)] * c))
return map(list, tuples)

557 Reverse Words in a String III

my solution:

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
lista=list()
s1=""
ret=""
for x in s:
if x!=' ':
s1+=x

else:
lista.append(s1)
s1=""

lista.append(s1) // append last string

print lista
for x in lista:
x=x[::-1]

ret+=x+' '

ret=ret[:-1] //delete last space, attention, last index is -1,and not included
return ret

better solution:
use python split function:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
                return " ".join(map(lamada x: x[ : :-1], s.split()))
                // note: " ".join will insert a space into join list element

62 unique path

  • By matrix:
	class Solution:
	def uniquePaths(self, m, n):
		 """
		:type m: int
		:type n: int
		:rtype: int
		 """
		 matrix = [[0 for j in range(n)] for i in range(m)]
		 matrix[0][0] = 1
		 for i in range(m):
			 for j in range(n):
				 if j > 0:
				 matrix[i][j] += matrix[i][j - 1]
				 if i > 0:
				 matrix[i][j] += matrix[i - 1][j]
		 return matrix[-1][-1]
  • By hashmap:
class Solution:
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dic = {(0, 0): 1}
        i, j = 0 , 1 
        while i < m:
            add1 = dic[(i, j - 1)] if j > 0 else 0
            add2 = dic[(i - 1, j)] if i > 0 else 0
            dic[(i, j)] = add1 + add2
            if j + 1 < n: j += 1
            else: i, j = i + 1, 0
        return dic[(m - 1, n - 1)] 

63. Unique Paths II

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        m=len(obstacleGrid)
        n=len(obstacleGrid[0])

        if obstacleGrid[0][0]==1:
            return 0

        obstacleGrid[0][0]=2

        for i in range(m):
            for j in range(n):
                if i>0 and obstacleGrid[i][j]!=1 :
                    obstacleGrid[i][j]+=obstacleGrid[i-1][j]
                    print "i=%d,j=%d, %d" %(i,j,obstacleGrid[i][j] )
                if j>0 and obstacleGrid[i][j]!=1 :
                    obstacleGrid[i][j]+=obstacleGrid[i][j-1]
                    print "xxx i=%d,j=%d, %d" %(i,j,obstacleGrid[i][j] )


        return obstacleGrid[-1][-1]/2

正确方式:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        ""
        :type obstacleGrid: List[List[int]]
        :rtype: int
        ""
        m=len(obstacleGrid)
        n=len(obstacleGrid[0])
        if obstacleGrid[0][0]==1:
            return 0
        obstacleGrid[0][0]=2
        for i in range(m):
            for j in range(n):
                if i>0 and obstacleGrid[i][j]!=1 and obstacleGrid[i-1][j]!=1:
                    obstacleGrid[i][j]+=obstacleGrid[i-1][j]
                if j>0 and obstacleGrid[i][j]!=1 and obstacleGrid[i][j-1]!=1:
                    obstacleGrid[i][j]+=obstacleGrid[i][j-1]
        return obstacleGrid[-1][-1]/2

when input is [0,1][0,0] the output will be 0,
python在进行二维数组遍历的时候,并非按照逐行后逐列的方式遍历,可能是先列后行。因此结果错误。

49. Group Anagrams

Tag: HashTable, String
我的code,超时,分析,时间复杂度应该是o(n^2),(1+n)n/2

# my solution , out of time
class Solution:
    def isAnagrams(self,a,b):
        dic1=dict()
        dic2=dict()
        for c in a:
            dic1[c]=dic1.get(c,0)+1
        for c in b:
            dic2[c]=dic2.get(c,0)+1
            
        return dic1==dic2
    def groupAnagrams(self, strs):
        """
        #:type strs: List[str]
        #:rtype: List[List[str]]
        """
        li=list()
        ret=list()
        
        for char in strs:
            a=bool()
            for i in range(len(ret)):
                if self.isAnagrams(char,ret[i][0]):
                    ret[i].append(char)
                    a=True
            if a==False:
                li.append(char)
                ret.append(li)
                li=[]
            a=False             
        return ret
                
        """
        for i in len(strs):
            j=i+1
            while j<len(strs):
                if isAnagrams(strs[i],strs[j]):
                    li.add(strs[j])
            
            if li!=[]:
                li.add(str[i])
            ret.add(li)
            li=[]
        return ret    
        """    

""""

从discuss中看到的,通用的做法是对元素先进行排序,然后通过hashmap进行索引,此种方法的复杂度与排序算法相关,python和C++ 都提供了O(NlogN)的复杂度的排序函数。

class Solution:
    def convert(self,s):
        lis=list(s)
        lis.sort()
        print(lis)
        return ''.join(lis)
    def groupAnagrams(self, strs):
        dic={}
        for str in strs:
            cons=self.convert(str)
            if cons in dic:
                dic[cons].append(str)
            else:
                dic[cons]=[str]
        return list(dic.values())
# solution 2
class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        groups = {}
        for s in strs:
            key = ''.join(sorted([c for c in s]))
            if key in groups:
                groups[key].append(s)
            else:
                groups[key] = [s]
        return list(groups.values())
# solution 3
class Solution:
    def groupAnagrams(self, strs):
        dic = collections.defaultdict(list)
        for s in strs: dic["".join(sorted(s))].append(s)
        return list(dic.values())        
        

python3 速度最快的解决方案

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d = {}
        for s in strs:
            ss = ''.join(sorted(s))
            if ss not in d:
                d[ss] = [s]
            else:
                d[ss].append(s)
        ans = []
        for key in d:
            ans.append(d[key])
        return ans

367. Valid Perfect Square

class Solution:
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        left=0
        right=num
        while left<right:
            mid=left+(right-left)//2
            if mid **2==num:
                return True
            elif mid**2<num:
                left=mid+1
            else: 
                right=mid
        
        if left==right and left **2==num:
            return True
        
        return False        

solution from discussion

Solving with Bitwise trick.
    def BitwiseTrick(self, num):
       root = 0
       bit = 1 << 15
       
       while bit > 0 :
           root |= bit
           if root > num // root:    
               root ^= bit                
           bit >>= 1        
       return root * root == num
Using Newton's Method
    def NewtonMethod(self, num):
        r = num
        while r*r > num:
            r = (r + num/r) // 2
        return r*r == num
Math Trick for Square number is 1+3+5+ ... +(2n-1)
    def Math(self, num):
        i = 1
        while (num>0):
            num -= i
            i += 2       
        return num == 0
Binary Search Method
    def BinarySearch(self, num):
        left = 0
        right = num
        
        while left <= right:
            mid = left + (right-left)//2
            if  mid ** 2 == num:
                return True
            elif mid ** 2 > num:
                right = mid -1
            else:
                left = mid +1
        return False
Linear Method (Naive) - For comparison
    def Linear(self, num):
        i = 1
        while i ** 2 <= num:
            if i ** 2 == num:
                return True
            else:
                i += 1
        return False
I test these five methods with for i in range(100000): function(i), and get results as below.

Time for Bitwise's Method : 0.45249104499816895
Time for Newton's Method : 0.3492701053619385
Time for Math's Method : 2.641957998275757
Time for Binary Search's Method : 1.5031492710113525
Time for Linear's Method : 17.613927125930786

6. ZigZag Conversionf

for easy understanding

/*n=numRows
Δ=2n-2    1                           2n-1                         4n-3
Δ=        2                     2n-2  2n                    4n-4   4n-2
Δ=        3               2n-3        2n+1              4n-5       .
Δ=        .           .               .               .            .
Δ=        .       n+2                 .           3n               .
Δ=        n-1 n+1                     3n-3    3n-1                 5n-5
Δ=2n-2    n                           3n-2                         5n-4
*/
class Solution {
public:
    string convert(string s, int numRows) {
        string result="";
        if(numRows==1)
			return s;
        int step1,step2;
        int len=s.size();
        for(int i=0;i<numRows;++i){
            step1=(numRows-i-1)*2;
            step2=(i)*2;
            int pos=i;
            if(pos<len)
                result+=s.at(pos);
            while(1){
                pos+=step1;
                if(pos>=len)
                    break;
				if(step1)
					result+=s.at(pos);
                pos+=step2;
                if(pos>=len)
                    break;
				if(step2)
					result+=s.at(pos);
            }
        }
        return result;
    }
};

112 path sum

my solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    count=0
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        self.count=self.count+1
        if root==None and sum==0:
            if self.count==1:
                return False
            else:
                return True
        
        if root==None and sum!=0:
            return False
        if root!=None:
            return  self.hasPathSum(root.left,sum-root.val) or  self.hasPathSum(root.right,sum-root.val)

final solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root==None:
            return False

        if root.val==sum and root.left==None and root.right==None:
            return True
        
        return  self.hasPathSum(root.left,sum-root.val) or  self.hasPathSum(root.right,sum-root.val)

84. Largest Rectangle in Histogram

class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        heights.append(0) 
        stack = [-1]   #add -1 to stack, this is magic code for me, keep stack never be None
        ans = 0
        for i in xrange(len(heights)):
            while heights[i] < heights[stack[-1]]:
                h = heights[stack.pop()] 
                w = i - stack[-1] - 1  # should minus 1 cause stack has been poped one time
                ans = max(ans, h * w)
            stack.append(i)
        heights.pop()
        return ans   

longest palindrome string length

36ms python solution

class Solution:
    def longestConsecutive(self, nums: 'List[int]') -> 'int':
        if not nums:
            return 0
        dict = {}
        for num in nums:
            dict[num] = 1
        res = 0
        for num in nums:
            if num - 1 not in dict:
                count = 1
                val = num
                val += 1
                while val in dict:
                    count += 1
                    val += 1
                res = max(res, count)
        return res

my solution:

class Solution(object):
    def longestConsecutive(self, nums):
        past=set(nums)
        maxlen=0
        for num in nums:
            s=num
            e=s
            while s-1 in nums:
                nums.remove(s-1)
                s=s-1
                
            while e+1 in nums:
                nums.remove(e+1)
                e=e+1
                
            maxlen=max(maxlen,e-s+1)
            
        return maxlen

141. Linked List Cycle

my solution

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head==None or head.next==None:
            return False
                    
        step1=head
        step2=head
        while step1.next!=None and step2.next.next!=None: 
            #note,first try,then given the pointer value
            step1=step1.next
            step2=step2.next.next #maybe not exit, so in while loop
            if step1==step2:
                return True
            
        return False

error:
==>NoneType has no attribute next
bug in:
step2=step2.next.next #maybe not exit, so in while loop

def hasCycle(self, head):
    try:
        slow = head
        fast = head.next
        while slow is not fast:
            slow = slow.next
            fast = fast.next.next
        return True
    except:
        return False
class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head: return False
        slow, fast = head, head.next
        while slow != fast:
            slow = slow.next
            if not fast:
                return False
            fast = fast.next
            if not fast:
                return False
            fast = fast.next
            if not fast:
                return False
        return True

141. Linked List Cycle II

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值