From d8248a989dc495dc5977a05c761ea5da594e8eb7 Mon Sep 17 00:00:00 2001 From: "Daniel D. ZHANG" Date: Sun, 21 Dec 2014 14:42:14 +0800 Subject: [PATCH] Line Ending --- .gitignore | 480 ++++++++++++++--------------- Backpack II.py | 58 ++-- Backpack.py | 148 ++++----- Binary Search.py | 62 ++-- Compare Strings.py | 42 +-- First Bad Version.py | 58 ++-- Hash Function.py | 48 +-- Majority Number.py | 82 ++--- Maximum Subarray Difference.py | 188 +++++------ Minimum Adjustment Cost.py | 94 +++--- Minimum Subarray.py | 70 ++--- Product of Array Exclude Itself.py | 60 ++-- README.md | 5 +- 13 files changed, 699 insertions(+), 696 deletions(-) diff --git a/.gitignore b/.gitignore index f5136fb..c462870 100644 --- a/.gitignore +++ b/.gitignore @@ -1,241 +1,241 @@ -################# -## Eclipse -################# - -*.pydevproject -.project -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.classpath -.settings/ -.loadpath -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath -Debug/ -Release/ - -################# -## Visual Studio -################# - -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.sln.docstates - -# Build results - -[Dd]ebug/ -[Rr]elease/ -x64/ -build/ -[Bb]in/ -[Oo]bj/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -*_i.c -*_p.c -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.log -*.scc - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -*.ncrunch* -.*crunch*.local.xml - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.Publish.xml -*.pubxml - -# NuGet Packages Directory -## TODO: If you have NuGet Package Restore enabled, uncomment the next line -#packages/ - -# Windows Azure Build Output -csx -*.build.csdef - -# Windows Store app package directory -AppPackages/ - -# Others -sql/ -*.Cache -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.[Pp]ublish.xml -*.pfx -*.publishsettings - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file to a newer -# Visual Studio version. Backup files are not needed, because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -App_Data/*.mdf -App_Data/*.ldf - -############# -## Windows detritus -############# - -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Mac crap -.DS_Store - - -############# -## Python -############# - -*.py[co] - -# Packages -*.egg -*.egg-info -dist/ -build/ -eggs/ -parts/ -var/ -sdist/ -develop-eggs/ -.installed.cfg - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox - -#Translations -*.mo - -#Mr Developer -.mr.developer.cfg -log/ -data/ -# python byte code -*.pyc - -############# -## Sublime -############# -# Ignore production server environment files -uwsgi_params -# sublime text -*.sublime-workspace - - -############# -## Idea -############# -.idea -.idea/ -*.eml -*.iml - -## I/O -*.in -*.out +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath +Debug/ +Release/ + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml +*.pubxml + +# NuGet Packages Directory +## TODO: If you have NuGet Package Restore enabled, uncomment the next line +#packages/ + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +App_Data/*.mdf +App_Data/*.ldf + +############# +## Windows detritus +############# + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac crap +.DS_Store + + +############# +## Python +############# + +*.py[co] + +# Packages +*.egg +*.egg-info +dist/ +build/ +eggs/ +parts/ +var/ +sdist/ +develop-eggs/ +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg +log/ +data/ +# python byte code +*.pyc + +############# +## Sublime +############# +# Ignore production server environment files +uwsgi_params +# sublime text +*.sublime-workspace + + +############# +## Idea +############# +.idea +.idea/ +*.eml +*.iml + +## I/O +*.in +*.out pdf/ \ No newline at end of file diff --git a/Backpack II.py b/Backpack II.py index 3661908..e241b49 100644 --- a/Backpack II.py +++ b/Backpack II.py @@ -1,30 +1,30 @@ -""" -Given n items with size A[i] and value V[i], and a backpack with size m. What's the maximum value can you put into the -backpack? -""" -__author__ = 'Danyang' -class Solution: - def backPackII(self, m, A, V): - """ - dp - f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]} - to - f[v]=max{f[v],f[v-c[i]+w[i]} - - NEED TO KEEP A COPY OF (i-1) STATE. - - :param m: An integer m denotes the size of a backpack - :param A & V: Given n items with size A[i] and value V[i] - :return: The maximum size - """ - n = len(A) - f = [0 for _ in xrange(m+1)] # plus 1 for dummy - for i in xrange(1, n+1): - copy = list(f) - for j in xrange(1, m+1): - # decide whether to put A[i-1] - if j-A[i-1]>=0: - f[j] = max(copy[j], copy[j-A[i-1]]+V[i-1]) - else: - f[j] = copy[j] +""" +Given n items with size A[i] and value V[i], and a backpack with size m. What's the maximum value can you put into the +backpack? +""" +__author__ = 'Danyang' +class Solution: + def backPackII(self, m, A, V): + """ + dp + f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]} + to + f[v]=max{f[v],f[v-c[i]+w[i]} + + NEED TO KEEP A COPY OF (i-1) STATE. + + :param m: An integer m denotes the size of a backpack + :param A & V: Given n items with size A[i] and value V[i] + :return: The maximum size + """ + n = len(A) + f = [0 for _ in xrange(m+1)] # plus 1 for dummy + for i in xrange(1, n+1): + copy = list(f) + for j in xrange(1, m+1): + # decide whether to put A[i-1] + if j-A[i-1]>=0: + f[j] = max(copy[j], copy[j-A[i-1]]+V[i-1]) + else: + f[j] = copy[j] return f[m] \ No newline at end of file diff --git a/Backpack.py b/Backpack.py index 86bbe3b..7001334 100644 --- a/Backpack.py +++ b/Backpack.py @@ -1,75 +1,75 @@ -""" -Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack? -""" -__author__ = 'Danyang' -class Solution_TLE: - def backPack(self, m, A): - """ - search, brute force - :param m: An integer m denotes the size of a backpack - :param A: Given n items with size A[i] - :return: The maximum size - """ - result = [0] - self.dfs(A, 0, m, result) - return result[0] - - def dfs(self, seq, cur, m, result): - if cur>m: - return - - result[0] = max(result[0], cur) - if seq: - self.dfs(seq[1:], cur+seq[0], m, result) - self.dfs(seq[1:], cur, m, result) - - -class Solution_MLE: - def backPack(self, m, A): - """ - dp - f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]} - - :param m: An integer m denotes the size of a backpack - :param A: Given n items with size A[i] - :return: The maximum size - """ - n = len(A) - f = [[0 for _ in xrange(m+1)] for _ in xrange(n+1)] # plus 1 for dummy - for i in xrange(1, n+1): - for j in xrange(1, m+1): - # decide whether to put A[i-1] - if j-A[i-1]>=0: - f[i][j] = max(f[i-1][j], f[i-1][j-A[i-1]]+A[i-1]) - else: - f[i][j] = f[i-1][j] - return f[n][m] - -class Solution: - def backPack(self, m, A): - """ - dp - f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]} - to - f[v]=max{f[v],f[v-c[i]+w[i]} - - NEED TO KEEP A COPY OF (i-1) STATE. - - :param m: An integer m denotes the size of a backpack - :param A: Given n items with size A[i] - :return: The maximum size - """ - n = len(A) - f = [0 for _ in xrange(m+1)] # plus 1 for dummy - for i in xrange(1, n+1): - copy = list(f) - for j in xrange(1, m+1): - # decide whether to put A[i-1] - if j-A[i-1]>=0: - f[j] = max(copy[j], copy[j-A[i-1]]+A[i-1]) - else: - f[j] = copy[j] - return f[m] - -if __name__=="__main__": +""" +Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack? +""" +__author__ = 'Danyang' +class Solution_TLE: + def backPack(self, m, A): + """ + search, brute force + :param m: An integer m denotes the size of a backpack + :param A: Given n items with size A[i] + :return: The maximum size + """ + result = [0] + self.dfs(A, 0, m, result) + return result[0] + + def dfs(self, seq, cur, m, result): + if cur>m: + return + + result[0] = max(result[0], cur) + if seq: + self.dfs(seq[1:], cur+seq[0], m, result) + self.dfs(seq[1:], cur, m, result) + + +class Solution_MLE: + def backPack(self, m, A): + """ + dp + f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]} + + :param m: An integer m denotes the size of a backpack + :param A: Given n items with size A[i] + :return: The maximum size + """ + n = len(A) + f = [[0 for _ in xrange(m+1)] for _ in xrange(n+1)] # plus 1 for dummy + for i in xrange(1, n+1): + for j in xrange(1, m+1): + # decide whether to put A[i-1] + if j-A[i-1]>=0: + f[i][j] = max(f[i-1][j], f[i-1][j-A[i-1]]+A[i-1]) + else: + f[i][j] = f[i-1][j] + return f[n][m] + +class Solution: + def backPack(self, m, A): + """ + dp + f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]} + to + f[v]=max{f[v],f[v-c[i]+w[i]} + + NEED TO KEEP A COPY OF (i-1) STATE. + + :param m: An integer m denotes the size of a backpack + :param A: Given n items with size A[i] + :return: The maximum size + """ + n = len(A) + f = [0 for _ in xrange(m+1)] # plus 1 for dummy + for i in xrange(1, n+1): + copy = list(f) + for j in xrange(1, m+1): + # decide whether to put A[i-1] + if j-A[i-1]>=0: + f[j] = max(copy[j], copy[j-A[i-1]]+A[i-1]) + else: + f[j] = copy[j] + return f[m] + +if __name__=="__main__": print Solution().backPack(11, [2, 3, 5, 7]) \ No newline at end of file diff --git a/Binary Search.py b/Binary Search.py index 582cc48..16924f2 100644 --- a/Binary Search.py +++ b/Binary Search.py @@ -1,31 +1,31 @@ -""" -Binary search is a famous question in algorithm. - -For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time -complexity. - -If the target number does not exist in the array, return -1. -""" -__author__ = 'Danyang' -class Solution: - def binarySearch(self, nums, target): - """ - basics - - :param nums: The integer array - :param target: Target number to find - :return the first position of target in nums, position start from 0 - """ - l = 0 - h = len(nums) - while l=0 and nums[mid-1]==nums[mid]: mid -= 1 - return mid - elif nums[mid]=0 and nums[mid-1]==nums[mid]: mid -= 1 + return mid + elif nums[mid]=0: - min_left[i] = min(current, min_left[i-1], min_left[i]) - else: - min_left[i] = min(current, min_left[i]) - - if current>0: - current = 0 - - # max subarray - current = 0 - for i in xrange(n): - current += nums[i] - if i-1>=0: - max_left[i] = max(current, max_left[i-1], max_left[i]) - else: - max_left[i] = max(current, max_left[i]) - - if current<0: - current = 0 - - current = 0 - for i in xrange(n-1, -1, -1): - current += nums[i] - if i+1<=n-1: - max_right[i] = max(current, max_right[i+1], max_right[i]) - else: - max_right[i] = max(current, max_right[i]) - - if current<0: - current = 0 - - current = 0 - for i in xrange(n-1, -1, -1): - current += nums[i] - if i+1<=n-1: - min_right[i] = min(current, min_right[i+1], min_right[i]) - else: - min_right[i] = min(current, min_right[i]) - - if current>0: - current = 0 - - maxa = 0 - for i in xrange(n-1): - maxa = max(maxa, abs(max_left[i]-min_right[i+1]), abs(min_left[i]-max_right[i+1])) - - return maxa - -if __name__=="__main__": - print Solution().maxDiffSubArrays([-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-1000]) - - - +""" +Given an array with integers. + +Find two non-overlapping subarrays A and B, which |SUM(A) - SUM(B)| is the largest. + +Return the largest difference. + +Note +The subarray should contain at least one number + +Example +For [1, 2, -3, 1], return 6 + +Challenge +O(n) time and O(n) space. +""" +__author__ = 'Danyang' +class Solution: + def maxDiffSubArrays(self, nums): + """ + Algorithm: dp + Maximum Subarray Difference + <= largest difference, max sum - min sum + <= max subarray sum and min subarray sum + <= because non-overlapping max/min subarray sum on one side, the other on the other side + <= split the array into half + + :param nums: A list of integers + :return: An integer indicate the value of maximum difference between two Subarrays + """ + n = len(nums) + min_left = list(nums) + max_left = list(nums) + min_right = list(nums) + max_right = list(nums) + + + # min subarray + current = 0 + for i in xrange(n): + current += nums[i] + if i-1>=0: + min_left[i] = min(current, min_left[i-1], min_left[i]) + else: + min_left[i] = min(current, min_left[i]) + + if current>0: + current = 0 + + # max subarray + current = 0 + for i in xrange(n): + current += nums[i] + if i-1>=0: + max_left[i] = max(current, max_left[i-1], max_left[i]) + else: + max_left[i] = max(current, max_left[i]) + + if current<0: + current = 0 + + current = 0 + for i in xrange(n-1, -1, -1): + current += nums[i] + if i+1<=n-1: + max_right[i] = max(current, max_right[i+1], max_right[i]) + else: + max_right[i] = max(current, max_right[i]) + + if current<0: + current = 0 + + current = 0 + for i in xrange(n-1, -1, -1): + current += nums[i] + if i+1<=n-1: + min_right[i] = min(current, min_right[i+1], min_right[i]) + else: + min_right[i] = min(current, min_right[i]) + + if current>0: + current = 0 + + maxa = 0 + for i in xrange(n-1): + maxa = max(maxa, abs(max_left[i]-min_right[i+1]), abs(min_left[i]-max_right[i+1])) + + return maxa + +if __name__=="__main__": + print Solution().maxDiffSubArrays([-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-4,5,-1000]) + + + diff --git a/Minimum Adjustment Cost.py b/Minimum Adjustment Cost.py index 9d181d2..92f63f2 100644 --- a/Minimum Adjustment Cost.py +++ b/Minimum Adjustment Cost.py @@ -1,47 +1,47 @@ -""" -Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a -given number target. - -If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]| - -Note -You can assume each number in the array is a positive integer and not greater than 100 - -Example -Given [1,4,2,3] and target=1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal. Return 2. -""" -__author__ = 'Danyang' -class Solution: - def MinAdjustmentCost(self, A, target): - """ - state dp - - f[i][j] = min(f[i-1][k] + |a[i]-j|, for k j-l to j+l) - - comments: similar to Vertibi algorithm (Hidden Markov Model) - - :param A: An integer array. - :param target: An integer. - """ - S = 100 - n = len(A) - f = [[1<<31 for _ in xrange(S+1)] for _ in xrange(n+1)] - - for j in xrange(S+1): - f[0][j] = 0 - - for i in xrange(1, n+1): - for j in xrange(1, S+1): - for k in xrange(max(1, j-target), min(S, j+target)+1): - f[i][j] = min(f[i][j], f[i-1][k]+abs(A[i-1]-j)) - - mini = 1<<31 - for j in xrange(1, S+1): - mini = min(mini, f[n][j]) - - return mini - - -if __name__=="__main__": - assert Solution().MinAdjustmentCost([12,3,7,4,5,13,2,8,4,7,6,5,7], 2)==19 - +""" +Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a +given number target. + +If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]| + +Note +You can assume each number in the array is a positive integer and not greater than 100 + +Example +Given [1,4,2,3] and target=1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal. Return 2. +""" +__author__ = 'Danyang' +class Solution: + def MinAdjustmentCost(self, A, target): + """ + state dp + + f[i][j] = min(f[i-1][k] + |a[i]-j|, for k j-l to j+l) + + comments: similar to Vertibi algorithm (Hidden Markov Model) + + :param A: An integer array. + :param target: An integer. + """ + S = 100 + n = len(A) + f = [[1<<31 for _ in xrange(S+1)] for _ in xrange(n+1)] + + for j in xrange(S+1): + f[0][j] = 0 + + for i in xrange(1, n+1): + for j in xrange(1, S+1): + for k in xrange(max(1, j-target), min(S, j+target)+1): + f[i][j] = min(f[i][j], f[i-1][k]+abs(A[i-1]-j)) + + mini = 1<<31 + for j in xrange(1, S+1): + mini = min(mini, f[n][j]) + + return mini + + +if __name__=="__main__": + assert Solution().MinAdjustmentCost([12,3,7,4,5,13,2,8,4,7,6,5,7], 2)==19 + diff --git a/Minimum Subarray.py b/Minimum Subarray.py index 47eeca7..9cfd15e 100644 --- a/Minimum Subarray.py +++ b/Minimum Subarray.py @@ -1,35 +1,35 @@ -""" -Given an array of integers, find the subarray with smallest sum. - -Return the sum of the subarray. - -Note -The subarray should contain at least one integer. - -Example -For [1, -1, -2, 1], return -3 -""" -__author__ = 'Danyang' -class Solution: - def minSubArray(self, nums): - """ - Greedy, dp - - :param nums: a list of integers - :return: A integer denote the sum of minimum subarray - """ - - mini = min(nums) - current = 0 - for a in nums: - current += a - mini = min(mini, current) - if current>0: - current = 0 - - return mini - -if __name__=="__main__": - assert Solution().minSubArray([1, -1, -2, 1])==-3 - - +""" +Given an array of integers, find the subarray with smallest sum. + +Return the sum of the subarray. + +Note +The subarray should contain at least one integer. + +Example +For [1, -1, -2, 1], return -3 +""" +__author__ = 'Danyang' +class Solution: + def minSubArray(self, nums): + """ + Greedy, dp + + :param nums: a list of integers + :return: A integer denote the sum of minimum subarray + """ + + mini = min(nums) + current = 0 + for a in nums: + current += a + mini = min(mini, current) + if current>0: + current = 0 + + return mini + +if __name__=="__main__": + assert Solution().minSubArray([1, -1, -2, 1])==-3 + + diff --git a/Product of Array Exclude Itself.py b/Product of Array Exclude Itself.py index 5cee85f..f70764c 100644 --- a/Product of Array Exclude Itself.py +++ b/Product of Array Exclude Itself.py @@ -1,30 +1,30 @@ -""" -Given an integers array A. - -Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B without divide operation. - -Example -For A=[1, 2, 3], B is [6, 3, 2] -""" -__author__ = 'Danyang' -class Solution: - def productExcludeItself(self, A): - """ - - :param A: Given an integers array A - :return: An integer array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] - """ - n = len(A) - if n==1: - return [] - - dp = [[1, 1] for _ in xrange(n)] - for i in xrange(1, n): - dp[i][0] = A[i-1]*dp[i-1][0] - dp[n-i-1][1] = A[n-i]*dp[n-i][1] - - B = [dp[i][0]*dp[i][1] for i in xrange(n)] - return B - -if __name__=="__main__": - print Solution().productExcludeItself([1, 2, 3]) +""" +Given an integers array A. + +Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B without divide operation. + +Example +For A=[1, 2, 3], B is [6, 3, 2] +""" +__author__ = 'Danyang' +class Solution: + def productExcludeItself(self, A): + """ + + :param A: Given an integers array A + :return: An integer array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] + """ + n = len(A) + if n==1: + return [] + + dp = [[1, 1] for _ in xrange(n)] + for i in xrange(1, n): + dp[i][0] = A[i-1]*dp[i-1][0] + dp[n-i-1][1] = A[n-i]*dp[n-i][1] + + B = [dp[i][0]*dp[i][1] for i in xrange(n)] + return B + +if __name__=="__main__": + print Solution().productExcludeItself([1, 2, 3]) diff --git a/README.md b/README.md index 90e5d22..022f050 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ # LintCode Python in Action. -Duplicated questions of [LeetCode](https://oj.leetcode.com/problems/) are excluded. Only unique questions from [LintCode](http://lintcode.com/) are included. +Duplicated questions of [LeetCode](https://oj.leetcode.com/problems/) are excluded. Only unique questions from [LintCode](http://lintcode.com/) are included. + +##LintCode Copyright +Most of the code are from the section of LintCode Copyright \ No newline at end of file