diff --git a/.DS_Store b/.DS_Store index 23a63a5..c842db5 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/Algorithm-CPP/.DS_Store b/Algorithm-CPP/.DS_Store new file mode 100644 index 0000000..7121468 Binary files /dev/null and b/Algorithm-CPP/.DS_Store differ diff --git a/Algorithm-CPP/Algorithm-C/collobert11a.xcworkspace/contents.xcworkspacedata b/Algorithm-CPP/Algorithm-C/collobert11a.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..88b0762 --- /dev/null +++ b/Algorithm-CPP/Algorithm-C/collobert11a.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Algorithm-CPP/Algorithm-C/collobert11a.xcworkspace/xcuserdata/sanqiangzhao.xcuserdatad/UserInterfaceState.xcuserstate b/Algorithm-CPP/Algorithm-C/collobert11a.xcworkspace/xcuserdata/sanqiangzhao.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..3b21a39 Binary files /dev/null and b/Algorithm-CPP/Algorithm-C/collobert11a.xcworkspace/xcuserdata/sanqiangzhao.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Algorithm-CPP/Algorithm-C/word-search.c b/Algorithm-CPP/Algorithm-C/word-search.c new file mode 100644 index 0000000..fc8a83a --- /dev/null +++ b/Algorithm-CPP/Algorithm-C/word-search.c @@ -0,0 +1,36 @@ +// +// word-search.c +// +// +// Created by Sanqiang Zhao on 11/25/15. +// +// + +#include "word-search.h" +bool existRecursive(char** board, int boardRowSize, int boardColSize, char* word, int idx, int nword,int row, int col){ + if (board[row][col] == word[idx]) { + char temp =board[row][col]; + board[row][col] = '*'; + if (idx == nword-1) { + return true; + }else if((row +1 < boardRowSize && board[row+1][col]!='*' && existRecursive(board,boardRowSize,boardColSize,word,idx+1,nword,row+1,col)) ||(row -1 >=0 && board[row-1][col]!='*' && existRecursive(board,boardRowSize,boardColSize,word,idx+1,nword,row-1,col)) ||(col +1 < boardColSize && board[row][col+1]!='*' && existRecursive(board,boardRowSize,boardColSize,word,idx+1,nword,row,col+1)) ||(col -1 >=0 && board[row][col-1]!='*' && existRecursive(board,boardRowSize,boardColSize,word,idx+1,nword,row,col-1))){ + return true; + } + board[row][col] =temp; + } + return false; +} + + +bool exist(char** board, int boardRowSize, int boardColSize, char* word) { + unsigned long nword = strlen(word); + + for (int row = 0; row < boardRowSize; ++row) { + for (int col = 0; col < boardColSize ; ++col) { + if(word[0] == board[row][col] && existRecursive(board,boardRowSize,boardColSize,word,0,nword,row,col)){ + return true; + } + } + } + return false; +} \ No newline at end of file diff --git a/Algorithm-CPP/Algorithm-C/word-search.h b/Algorithm-CPP/Algorithm-C/word-search.h new file mode 100644 index 0000000..7ae7bfa --- /dev/null +++ b/Algorithm-CPP/Algorithm-C/word-search.h @@ -0,0 +1,14 @@ +// +// word-search.h +// +// +// Created by Sanqiang Zhao on 11/25/15. +// +// + +#ifndef word_search_h +#define word_search_h + +#include + +#endif /* word_search_h */ diff --git a/Algorithm-Linux.xcodeproj/project.pbxproj b/Algorithm-CPP/Algorithm-Linux.xcodeproj/project.pbxproj similarity index 100% rename from Algorithm-Linux.xcodeproj/project.pbxproj rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/project.pbxproj diff --git a/Algorithm-Linux.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Algorithm-CPP/Algorithm-Linux.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Algorithm-Linux.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/UserInterfaceState.xcuserstate b/Algorithm-CPP/Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/UserInterfaceState.xcuserstate similarity index 100% rename from Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/UserInterfaceState.xcuserstate rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/UserInterfaceState.xcuserstate diff --git a/Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Expressions.xcexplist b/Algorithm-CPP/Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Expressions.xcexplist similarity index 100% rename from Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Expressions.xcexplist rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/project.xcworkspace/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Expressions.xcexplist diff --git a/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/Algorithm-CPP/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist similarity index 100% rename from Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist diff --git a/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/Algorithm-Linux.xcscheme b/Algorithm-CPP/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/Algorithm-Linux.xcscheme similarity index 100% rename from Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/Algorithm-Linux.xcscheme rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/Algorithm-Linux.xcscheme diff --git a/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/xcschememanagement.plist b/Algorithm-CPP/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/xcschememanagement.plist similarity index 100% rename from Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/xcschememanagement.plist rename to Algorithm-CPP/Algorithm-Linux.xcodeproj/xcuserdata/zhaosanqiang916.xcuserdatad/xcschemes/xcschememanagement.plist diff --git a/Entity.cpp b/Algorithm-CPP/Entity.cpp similarity index 100% rename from Entity.cpp rename to Algorithm-CPP/Entity.cpp diff --git a/Entity.h b/Algorithm-CPP/Entity.h similarity index 100% rename from Entity.h rename to Algorithm-CPP/Entity.h diff --git a/KMP.cpp b/Algorithm-CPP/KMP.cpp similarity index 100% rename from KMP.cpp rename to Algorithm-CPP/KMP.cpp diff --git a/KMP.h b/Algorithm-CPP/KMP.h similarity index 100% rename from KMP.h rename to Algorithm-CPP/KMP.h diff --git a/Q11-VerifyUniqueCharInString.cpp b/Algorithm-CPP/Q11-VerifyUniqueCharInString.cpp similarity index 100% rename from Q11-VerifyUniqueCharInString.cpp rename to Algorithm-CPP/Q11-VerifyUniqueCharInString.cpp diff --git a/Q11-VerifyUniqueCharInString.h b/Algorithm-CPP/Q11-VerifyUniqueCharInString.h similarity index 100% rename from Q11-VerifyUniqueCharInString.h rename to Algorithm-CPP/Q11-VerifyUniqueCharInString.h diff --git a/Q111-MergeSortedArray.cpp b/Algorithm-CPP/Q111-MergeSortedArray.cpp similarity index 100% rename from Q111-MergeSortedArray.cpp rename to Algorithm-CPP/Q111-MergeSortedArray.cpp diff --git a/Q111-MergeSortedArray.h b/Algorithm-CPP/Q111-MergeSortedArray.h similarity index 100% rename from Q111-MergeSortedArray.h rename to Algorithm-CPP/Q111-MergeSortedArray.h diff --git a/Q112-SortString.cpp b/Algorithm-CPP/Q112-SortString.cpp similarity index 100% rename from Q112-SortString.cpp rename to Algorithm-CPP/Q112-SortString.cpp diff --git a/Q112-SortString.h b/Algorithm-CPP/Q112-SortString.h similarity index 100% rename from Q112-SortString.h rename to Algorithm-CPP/Q112-SortString.h diff --git a/Q113-FindInRotatedArr.cpp b/Algorithm-CPP/Q113-FindInRotatedArr.cpp similarity index 100% rename from Q113-FindInRotatedArr.cpp rename to Algorithm-CPP/Q113-FindInRotatedArr.cpp diff --git a/Q113-FindInRotatedArr.h b/Algorithm-CPP/Q113-FindInRotatedArr.h similarity index 100% rename from Q113-FindInRotatedArr.h rename to Algorithm-CPP/Q113-FindInRotatedArr.h diff --git a/Q115-FindStringInIntersperse.cpp b/Algorithm-CPP/Q115-FindStringInIntersperse.cpp similarity index 100% rename from Q115-FindStringInIntersperse.cpp rename to Algorithm-CPP/Q115-FindStringInIntersperse.cpp diff --git a/Q115-FindStringInIntersperse.h b/Algorithm-CPP/Q115-FindStringInIntersperse.h similarity index 100% rename from Q115-FindStringInIntersperse.h rename to Algorithm-CPP/Q115-FindStringInIntersperse.h diff --git a/Q116-SearchOnMatrix.cpp b/Algorithm-CPP/Q116-SearchOnMatrix.cpp similarity index 100% rename from Q116-SearchOnMatrix.cpp rename to Algorithm-CPP/Q116-SearchOnMatrix.cpp diff --git a/Q116-SearchOnMatrix.h b/Algorithm-CPP/Q116-SearchOnMatrix.h similarity index 100% rename from Q116-SearchOnMatrix.h rename to Algorithm-CPP/Q116-SearchOnMatrix.h diff --git a/Q117-LongestIncreasingSequence.cpp b/Algorithm-CPP/Q117-LongestIncreasingSequence.cpp similarity index 100% rename from Q117-LongestIncreasingSequence.cpp rename to Algorithm-CPP/Q117-LongestIncreasingSequence.cpp diff --git a/Q117-LongestIncreasingSequence.h b/Algorithm-CPP/Q117-LongestIncreasingSequence.h similarity index 100% rename from Q117-LongestIncreasingSequence.h rename to Algorithm-CPP/Q117-LongestIncreasingSequence.h diff --git a/Q118-TrackBinarySearchTree.cpp b/Algorithm-CPP/Q118-TrackBinarySearchTree.cpp similarity index 100% rename from Q118-TrackBinarySearchTree.cpp rename to Algorithm-CPP/Q118-TrackBinarySearchTree.cpp diff --git a/Q118-TrackBinarySearchTree.h b/Algorithm-CPP/Q118-TrackBinarySearchTree.h similarity index 100% rename from Q118-TrackBinarySearchTree.h rename to Algorithm-CPP/Q118-TrackBinarySearchTree.h diff --git a/Q12-ReverseString.cpp b/Algorithm-CPP/Q12-ReverseString.cpp similarity index 100% rename from Q12-ReverseString.cpp rename to Algorithm-CPP/Q12-ReverseString.cpp diff --git a/Q12-ReverseString.h b/Algorithm-CPP/Q12-ReverseString.h similarity index 100% rename from Q12-ReverseString.h rename to Algorithm-CPP/Q12-ReverseString.h diff --git a/Q13-VerifyAnagram.cpp b/Algorithm-CPP/Q13-VerifyAnagram.cpp similarity index 100% rename from Q13-VerifyAnagram.cpp rename to Algorithm-CPP/Q13-VerifyAnagram.cpp diff --git a/Q13-VerifyAnagram.h b/Algorithm-CPP/Q13-VerifyAnagram.h similarity index 100% rename from Q13-VerifyAnagram.h rename to Algorithm-CPP/Q13-VerifyAnagram.h diff --git a/Q14-encodeUrl.cpp b/Algorithm-CPP/Q14-encodeUrl.cpp similarity index 100% rename from Q14-encodeUrl.cpp rename to Algorithm-CPP/Q14-encodeUrl.cpp diff --git a/Q14-encodeUrl.h b/Algorithm-CPP/Q14-encodeUrl.h similarity index 100% rename from Q14-encodeUrl.h rename to Algorithm-CPP/Q14-encodeUrl.h diff --git a/Q15-compressStr.cpp b/Algorithm-CPP/Q15-compressStr.cpp similarity index 100% rename from Q15-compressStr.cpp rename to Algorithm-CPP/Q15-compressStr.cpp diff --git a/Q15-compressStr.h b/Algorithm-CPP/Q15-compressStr.h similarity index 100% rename from Q15-compressStr.h rename to Algorithm-CPP/Q15-compressStr.h diff --git a/Q16-rotateMatrix.cpp b/Algorithm-CPP/Q16-rotateMatrix.cpp similarity index 100% rename from Q16-rotateMatrix.cpp rename to Algorithm-CPP/Q16-rotateMatrix.cpp diff --git a/Q16-rotateMatrix.h b/Algorithm-CPP/Q16-rotateMatrix.h similarity index 100% rename from Q16-rotateMatrix.h rename to Algorithm-CPP/Q16-rotateMatrix.h diff --git a/Q17-SetZeroOnMatrix.cpp b/Algorithm-CPP/Q17-SetZeroOnMatrix.cpp similarity index 100% rename from Q17-SetZeroOnMatrix.cpp rename to Algorithm-CPP/Q17-SetZeroOnMatrix.cpp diff --git a/Q17-SetZeroOnMatrix.h b/Algorithm-CPP/Q17-SetZeroOnMatrix.h similarity index 100% rename from Q17-SetZeroOnMatrix.h rename to Algorithm-CPP/Q17-SetZeroOnMatrix.h diff --git a/Q18-VerifyRotation.cpp b/Algorithm-CPP/Q18-VerifyRotation.cpp similarity index 100% rename from Q18-VerifyRotation.cpp rename to Algorithm-CPP/Q18-VerifyRotation.cpp diff --git a/Q18-VerifyRotation.h b/Algorithm-CPP/Q18-VerifyRotation.h similarity index 100% rename from Q18-VerifyRotation.h rename to Algorithm-CPP/Q18-VerifyRotation.h diff --git a/Q2-ReverseString.cpp b/Algorithm-CPP/Q2-ReverseString.cpp similarity index 100% rename from Q2-ReverseString.cpp rename to Algorithm-CPP/Q2-ReverseString.cpp diff --git a/Q2-ReverseString.h b/Algorithm-CPP/Q2-ReverseString.h similarity index 100% rename from Q2-ReverseString.h rename to Algorithm-CPP/Q2-ReverseString.h diff --git a/Q21-removeDuplacate.cpp b/Algorithm-CPP/Q21-removeDuplacate.cpp similarity index 100% rename from Q21-removeDuplacate.cpp rename to Algorithm-CPP/Q21-removeDuplacate.cpp diff --git a/Q21-removeDuplacate.h b/Algorithm-CPP/Q21-removeDuplacate.h similarity index 100% rename from Q21-removeDuplacate.h rename to Algorithm-CPP/Q21-removeDuplacate.h diff --git a/Q22-findLastNthElement.cpp b/Algorithm-CPP/Q22-findLastNthElement.cpp similarity index 100% rename from Q22-findLastNthElement.cpp rename to Algorithm-CPP/Q22-findLastNthElement.cpp diff --git a/Q22-findLastNthElement.h b/Algorithm-CPP/Q22-findLastNthElement.h similarity index 100% rename from Q22-findLastNthElement.h rename to Algorithm-CPP/Q22-findLastNthElement.h diff --git a/Q23-deleteElement.cpp b/Algorithm-CPP/Q23-deleteElement.cpp similarity index 100% rename from Q23-deleteElement.cpp rename to Algorithm-CPP/Q23-deleteElement.cpp diff --git a/Q23-deleteElement.h b/Algorithm-CPP/Q23-deleteElement.h similarity index 100% rename from Q23-deleteElement.h rename to Algorithm-CPP/Q23-deleteElement.h diff --git a/Q24-PartitionLinkedList.cpp b/Algorithm-CPP/Q24-PartitionLinkedList.cpp similarity index 100% rename from Q24-PartitionLinkedList.cpp rename to Algorithm-CPP/Q24-PartitionLinkedList.cpp diff --git a/Q24-PartitionLinkedList.h b/Algorithm-CPP/Q24-PartitionLinkedList.h similarity index 100% rename from Q24-PartitionLinkedList.h rename to Algorithm-CPP/Q24-PartitionLinkedList.h diff --git a/Q25-AddLinkedList.cpp b/Algorithm-CPP/Q25-AddLinkedList.cpp similarity index 100% rename from Q25-AddLinkedList.cpp rename to Algorithm-CPP/Q25-AddLinkedList.cpp diff --git a/Q25-AddLinkedList.h b/Algorithm-CPP/Q25-AddLinkedList.h similarity index 100% rename from Q25-AddLinkedList.h rename to Algorithm-CPP/Q25-AddLinkedList.h diff --git a/Q26-findEntryInCircularList.cpp b/Algorithm-CPP/Q26-findEntryInCircularList.cpp similarity index 100% rename from Q26-findEntryInCircularList.cpp rename to Algorithm-CPP/Q26-findEntryInCircularList.cpp diff --git a/Q26-findEntryInCircularList.h b/Algorithm-CPP/Q26-findEntryInCircularList.h similarity index 100% rename from Q26-findEntryInCircularList.h rename to Algorithm-CPP/Q26-findEntryInCircularList.h diff --git a/Q27-VerifyPalindrome.cpp b/Algorithm-CPP/Q27-VerifyPalindrome.cpp similarity index 100% rename from Q27-VerifyPalindrome.cpp rename to Algorithm-CPP/Q27-VerifyPalindrome.cpp diff --git a/Q27-VerifyPalindrome.h b/Algorithm-CPP/Q27-VerifyPalindrome.h similarity index 100% rename from Q27-VerifyPalindrome.h rename to Algorithm-CPP/Q27-VerifyPalindrome.h diff --git a/Q3-VerifyAnagram.cpp b/Algorithm-CPP/Q3-VerifyAnagram.cpp similarity index 100% rename from Q3-VerifyAnagram.cpp rename to Algorithm-CPP/Q3-VerifyAnagram.cpp diff --git a/Q3-VerifyAnagram.h b/Algorithm-CPP/Q3-VerifyAnagram.h similarity index 100% rename from Q3-VerifyAnagram.h rename to Algorithm-CPP/Q3-VerifyAnagram.h diff --git a/Q31-ThreeStacksFromOneArray.cpp b/Algorithm-CPP/Q31-ThreeStacksFromOneArray.cpp similarity index 100% rename from Q31-ThreeStacksFromOneArray.cpp rename to Algorithm-CPP/Q31-ThreeStacksFromOneArray.cpp diff --git a/Q31-ThreeStacksFromOneArray.h b/Algorithm-CPP/Q31-ThreeStacksFromOneArray.h similarity index 100% rename from Q31-ThreeStacksFromOneArray.h rename to Algorithm-CPP/Q31-ThreeStacksFromOneArray.h diff --git a/Q32-StackWithMin.cpp b/Algorithm-CPP/Q32-StackWithMin.cpp similarity index 100% rename from Q32-StackWithMin.cpp rename to Algorithm-CPP/Q32-StackWithMin.cpp diff --git a/Q32-StackWithMin.h b/Algorithm-CPP/Q32-StackWithMin.h similarity index 100% rename from Q32-StackWithMin.h rename to Algorithm-CPP/Q32-StackWithMin.h diff --git a/Q33-SetOfStacks.cpp b/Algorithm-CPP/Q33-SetOfStacks.cpp similarity index 100% rename from Q33-SetOfStacks.cpp rename to Algorithm-CPP/Q33-SetOfStacks.cpp diff --git a/Q33-SetOfStacks.h b/Algorithm-CPP/Q33-SetOfStacks.h similarity index 100% rename from Q33-SetOfStacks.h rename to Algorithm-CPP/Q33-SetOfStacks.h diff --git a/Q34-TowersOfHanoi.cpp b/Algorithm-CPP/Q34-TowersOfHanoi.cpp similarity index 100% rename from Q34-TowersOfHanoi.cpp rename to Algorithm-CPP/Q34-TowersOfHanoi.cpp diff --git a/Q34-TowersOfHanoi.h b/Algorithm-CPP/Q34-TowersOfHanoi.h similarity index 100% rename from Q34-TowersOfHanoi.h rename to Algorithm-CPP/Q34-TowersOfHanoi.h diff --git a/Q35-QueueWithTwoStacks.cpp b/Algorithm-CPP/Q35-QueueWithTwoStacks.cpp similarity index 100% rename from Q35-QueueWithTwoStacks.cpp rename to Algorithm-CPP/Q35-QueueWithTwoStacks.cpp diff --git a/Q35-QueueWithTwoStacks.h b/Algorithm-CPP/Q35-QueueWithTwoStacks.h similarity index 100% rename from Q35-QueueWithTwoStacks.h rename to Algorithm-CPP/Q35-QueueWithTwoStacks.h diff --git a/Q36-SortStack.cpp b/Algorithm-CPP/Q36-SortStack.cpp similarity index 100% rename from Q36-SortStack.cpp rename to Algorithm-CPP/Q36-SortStack.cpp diff --git a/Q36-SortStack.h b/Algorithm-CPP/Q36-SortStack.h similarity index 100% rename from Q36-SortStack.h rename to Algorithm-CPP/Q36-SortStack.h diff --git a/Q37-AnimalShelter.cpp b/Algorithm-CPP/Q37-AnimalShelter.cpp similarity index 100% rename from Q37-AnimalShelter.cpp rename to Algorithm-CPP/Q37-AnimalShelter.cpp diff --git a/Q37-AnimalShelter.h b/Algorithm-CPP/Q37-AnimalShelter.h similarity index 100% rename from Q37-AnimalShelter.h rename to Algorithm-CPP/Q37-AnimalShelter.h diff --git a/Q41-CheckBalanceTree.cpp b/Algorithm-CPP/Q41-CheckBalanceTree.cpp similarity index 100% rename from Q41-CheckBalanceTree.cpp rename to Algorithm-CPP/Q41-CheckBalanceTree.cpp diff --git a/Q41-CheckBalanceTree.h b/Algorithm-CPP/Q41-CheckBalanceTree.h similarity index 100% rename from Q41-CheckBalanceTree.h rename to Algorithm-CPP/Q41-CheckBalanceTree.h diff --git a/Q42-FindRouteBFS.cpp b/Algorithm-CPP/Q42-FindRouteBFS.cpp similarity index 100% rename from Q42-FindRouteBFS.cpp rename to Algorithm-CPP/Q42-FindRouteBFS.cpp diff --git a/Q42-FindRouteBFS.h b/Algorithm-CPP/Q42-FindRouteBFS.h similarity index 100% rename from Q42-FindRouteBFS.h rename to Algorithm-CPP/Q42-FindRouteBFS.h diff --git a/Q43-BinarySearchTreeFromSortedArray.cpp b/Algorithm-CPP/Q43-BinarySearchTreeFromSortedArray.cpp similarity index 100% rename from Q43-BinarySearchTreeFromSortedArray.cpp rename to Algorithm-CPP/Q43-BinarySearchTreeFromSortedArray.cpp diff --git a/Q43-BinarySearchTreeFromSortedArray.h b/Algorithm-CPP/Q43-BinarySearchTreeFromSortedArray.h similarity index 100% rename from Q43-BinarySearchTreeFromSortedArray.h rename to Algorithm-CPP/Q43-BinarySearchTreeFromSortedArray.h diff --git a/Q44-BuildLinkedListFromTreeBFS.cpp b/Algorithm-CPP/Q44-BuildLinkedListFromTreeBFS.cpp similarity index 100% rename from Q44-BuildLinkedListFromTreeBFS.cpp rename to Algorithm-CPP/Q44-BuildLinkedListFromTreeBFS.cpp diff --git a/Q44-BuildLinkedListFromTreeBFS.h b/Algorithm-CPP/Q44-BuildLinkedListFromTreeBFS.h similarity index 100% rename from Q44-BuildLinkedListFromTreeBFS.h rename to Algorithm-CPP/Q44-BuildLinkedListFromTreeBFS.h diff --git a/Q45-CheckBinarySearchTree.cpp b/Algorithm-CPP/Q45-CheckBinarySearchTree.cpp similarity index 100% rename from Q45-CheckBinarySearchTree.cpp rename to Algorithm-CPP/Q45-CheckBinarySearchTree.cpp diff --git a/Q45-CheckBinarySearchTree.h b/Algorithm-CPP/Q45-CheckBinarySearchTree.h similarity index 100% rename from Q45-CheckBinarySearchTree.h rename to Algorithm-CPP/Q45-CheckBinarySearchTree.h diff --git a/Q46-NextOnBinaryTree.cpp b/Algorithm-CPP/Q46-NextOnBinaryTree.cpp similarity index 100% rename from Q46-NextOnBinaryTree.cpp rename to Algorithm-CPP/Q46-NextOnBinaryTree.cpp diff --git a/Q46-NextOnBinaryTree.h b/Algorithm-CPP/Q46-NextOnBinaryTree.h similarity index 100% rename from Q46-NextOnBinaryTree.h rename to Algorithm-CPP/Q46-NextOnBinaryTree.h diff --git a/Q47-FindCommonAncester.cpp b/Algorithm-CPP/Q47-FindCommonAncester.cpp similarity index 100% rename from Q47-FindCommonAncester.cpp rename to Algorithm-CPP/Q47-FindCommonAncester.cpp diff --git a/Q47-FindCommonAncester.h b/Algorithm-CPP/Q47-FindCommonAncester.h similarity index 100% rename from Q47-FindCommonAncester.h rename to Algorithm-CPP/Q47-FindCommonAncester.h diff --git a/Q48-CheckSubTree.cpp b/Algorithm-CPP/Q48-CheckSubTree.cpp similarity index 100% rename from Q48-CheckSubTree.cpp rename to Algorithm-CPP/Q48-CheckSubTree.cpp diff --git a/Q48-CheckSubTree.h b/Algorithm-CPP/Q48-CheckSubTree.h similarity index 100% rename from Q48-CheckSubTree.h rename to Algorithm-CPP/Q48-CheckSubTree.h diff --git a/Q49-FindSumBFS.cpp b/Algorithm-CPP/Q49-FindSumBFS.cpp similarity index 100% rename from Q49-FindSumBFS.cpp rename to Algorithm-CPP/Q49-FindSumBFS.cpp diff --git a/Q49-FindSumBFS.h b/Algorithm-CPP/Q49-FindSumBFS.h similarity index 100% rename from Q49-FindSumBFS.h rename to Algorithm-CPP/Q49-FindSumBFS.h diff --git a/Q51-UpdateBitOnMN.cpp b/Algorithm-CPP/Q51-UpdateBitOnMN.cpp similarity index 100% rename from Q51-UpdateBitOnMN.cpp rename to Algorithm-CPP/Q51-UpdateBitOnMN.cpp diff --git a/Q51-UpdateBitOnMN.h b/Algorithm-CPP/Q51-UpdateBitOnMN.h similarity index 100% rename from Q51-UpdateBitOnMN.h rename to Algorithm-CPP/Q51-UpdateBitOnMN.h diff --git a/Q52-PrintBinary.cpp b/Algorithm-CPP/Q52-PrintBinary.cpp similarity index 100% rename from Q52-PrintBinary.cpp rename to Algorithm-CPP/Q52-PrintBinary.cpp diff --git a/Q52-PrintBinary.h b/Algorithm-CPP/Q52-PrintBinary.h similarity index 100% rename from Q52-PrintBinary.h rename to Algorithm-CPP/Q52-PrintBinary.h diff --git a/Q53-NextNumWithSameBit.cpp b/Algorithm-CPP/Q53-NextNumWithSameBit.cpp similarity index 100% rename from Q53-NextNumWithSameBit.cpp rename to Algorithm-CPP/Q53-NextNumWithSameBit.cpp diff --git a/Q53-NextNumWithSameBit.h b/Algorithm-CPP/Q53-NextNumWithSameBit.h similarity index 100% rename from Q53-NextNumWithSameBit.h rename to Algorithm-CPP/Q53-NextNumWithSameBit.h diff --git a/Q55-BitSwapRequired.cpp b/Algorithm-CPP/Q55-BitSwapRequired.cpp similarity index 100% rename from Q55-BitSwapRequired.cpp rename to Algorithm-CPP/Q55-BitSwapRequired.cpp diff --git a/Q55-BitSwapRequired.h b/Algorithm-CPP/Q55-BitSwapRequired.h similarity index 100% rename from Q55-BitSwapRequired.h rename to Algorithm-CPP/Q55-BitSwapRequired.h diff --git a/Q56-SwapOddEvenBit.cpp b/Algorithm-CPP/Q56-SwapOddEvenBit.cpp similarity index 100% rename from Q56-SwapOddEvenBit.cpp rename to Algorithm-CPP/Q56-SwapOddEvenBit.cpp diff --git a/Q56-SwapOddEvenBit.h b/Algorithm-CPP/Q56-SwapOddEvenBit.h similarity index 100% rename from Q56-SwapOddEvenBit.h rename to Algorithm-CPP/Q56-SwapOddEvenBit.h diff --git a/Q57-FindMissing.cpp b/Algorithm-CPP/Q57-FindMissing.cpp similarity index 100% rename from Q57-FindMissing.cpp rename to Algorithm-CPP/Q57-FindMissing.cpp diff --git a/Q57-FindMissing.h b/Algorithm-CPP/Q57-FindMissing.h similarity index 100% rename from Q57-FindMissing.h rename to Algorithm-CPP/Q57-FindMissing.h diff --git a/Q58-DrawHorizontalLine.cpp b/Algorithm-CPP/Q58-DrawHorizontalLine.cpp similarity index 100% rename from Q58-DrawHorizontalLine.cpp rename to Algorithm-CPP/Q58-DrawHorizontalLine.cpp diff --git a/Q58-DrawHorizontalLine.h b/Algorithm-CPP/Q58-DrawHorizontalLine.h similarity index 100% rename from Q58-DrawHorizontalLine.h rename to Algorithm-CPP/Q58-DrawHorizontalLine.h diff --git a/Q91-CountWaysOnStairs.cpp b/Algorithm-CPP/Q91-CountWaysOnStairs.cpp similarity index 100% rename from Q91-CountWaysOnStairs.cpp rename to Algorithm-CPP/Q91-CountWaysOnStairs.cpp diff --git a/Q91-CountWaysOnStairs.h b/Algorithm-CPP/Q91-CountWaysOnStairs.h similarity index 100% rename from Q91-CountWaysOnStairs.h rename to Algorithm-CPP/Q91-CountWaysOnStairs.h diff --git a/Q910-CreateStackBox.cpp b/Algorithm-CPP/Q910-CreateStackBox.cpp similarity index 100% rename from Q910-CreateStackBox.cpp rename to Algorithm-CPP/Q910-CreateStackBox.cpp diff --git a/Q910-CreateStackBox.h b/Algorithm-CPP/Q910-CreateStackBox.h similarity index 100% rename from Q910-CreateStackBox.h rename to Algorithm-CPP/Q910-CreateStackBox.h diff --git a/Q911-BinaryPresentation.cpp b/Algorithm-CPP/Q911-BinaryPresentation.cpp similarity index 100% rename from Q911-BinaryPresentation.cpp rename to Algorithm-CPP/Q911-BinaryPresentation.cpp diff --git a/Q911-BinaryPresentation.h b/Algorithm-CPP/Q911-BinaryPresentation.h similarity index 100% rename from Q911-BinaryPresentation.h rename to Algorithm-CPP/Q911-BinaryPresentation.h diff --git a/Q92-RobotMovement.cpp b/Algorithm-CPP/Q92-RobotMovement.cpp similarity index 100% rename from Q92-RobotMovement.cpp rename to Algorithm-CPP/Q92-RobotMovement.cpp diff --git a/Q92-RobotMovement.h b/Algorithm-CPP/Q92-RobotMovement.h similarity index 100% rename from Q92-RobotMovement.h rename to Algorithm-CPP/Q92-RobotMovement.h diff --git a/Q93-FindMagicIndex.cpp b/Algorithm-CPP/Q93-FindMagicIndex.cpp similarity index 100% rename from Q93-FindMagicIndex.cpp rename to Algorithm-CPP/Q93-FindMagicIndex.cpp diff --git a/Q93-FindMagicIndex.h b/Algorithm-CPP/Q93-FindMagicIndex.h similarity index 100% rename from Q93-FindMagicIndex.h rename to Algorithm-CPP/Q93-FindMagicIndex.h diff --git a/Q94-Subsets.cpp b/Algorithm-CPP/Q94-Subsets.cpp similarity index 100% rename from Q94-Subsets.cpp rename to Algorithm-CPP/Q94-Subsets.cpp diff --git a/Q94-Subsets.h b/Algorithm-CPP/Q94-Subsets.h similarity index 100% rename from Q94-Subsets.h rename to Algorithm-CPP/Q94-Subsets.h diff --git a/Q95-Permutation.cpp b/Algorithm-CPP/Q95-Permutation.cpp similarity index 100% rename from Q95-Permutation.cpp rename to Algorithm-CPP/Q95-Permutation.cpp diff --git a/Q95-Permutation.h b/Algorithm-CPP/Q95-Permutation.h similarity index 100% rename from Q95-Permutation.h rename to Algorithm-CPP/Q95-Permutation.h diff --git a/Q96-ValidParenthesis.cpp b/Algorithm-CPP/Q96-ValidParenthesis.cpp similarity index 100% rename from Q96-ValidParenthesis.cpp rename to Algorithm-CPP/Q96-ValidParenthesis.cpp diff --git a/Q96-ValidParenthesis.h b/Algorithm-CPP/Q96-ValidParenthesis.h similarity index 100% rename from Q96-ValidParenthesis.h rename to Algorithm-CPP/Q96-ValidParenthesis.h diff --git a/Q97-FillColor.cpp b/Algorithm-CPP/Q97-FillColor.cpp similarity index 100% rename from Q97-FillColor.cpp rename to Algorithm-CPP/Q97-FillColor.cpp diff --git a/Q97-FillColor.h b/Algorithm-CPP/Q97-FillColor.h similarity index 100% rename from Q97-FillColor.h rename to Algorithm-CPP/Q97-FillColor.h diff --git a/Q98-MakeCoinCharges.cpp b/Algorithm-CPP/Q98-MakeCoinCharges.cpp similarity index 100% rename from Q98-MakeCoinCharges.cpp rename to Algorithm-CPP/Q98-MakeCoinCharges.cpp diff --git a/Q98-MakeCoinCharges.h b/Algorithm-CPP/Q98-MakeCoinCharges.h similarity index 100% rename from Q98-MakeCoinCharges.h rename to Algorithm-CPP/Q98-MakeCoinCharges.h diff --git a/Q99-PlaceQueen.cpp b/Algorithm-CPP/Q99-PlaceQueen.cpp similarity index 100% rename from Q99-PlaceQueen.cpp rename to Algorithm-CPP/Q99-PlaceQueen.cpp diff --git a/Q99-PlaceQueen.h b/Algorithm-CPP/Q99-PlaceQueen.h similarity index 100% rename from Q99-PlaceQueen.h rename to Algorithm-CPP/Q99-PlaceQueen.h diff --git a/QuickSort.cpp b/Algorithm-CPP/QuickSort.cpp similarity index 100% rename from QuickSort.cpp rename to Algorithm-CPP/QuickSort.cpp diff --git a/QuickSort.h b/Algorithm-CPP/QuickSort.h similarity index 100% rename from QuickSort.h rename to Algorithm-CPP/QuickSort.h diff --git a/README.md b/Algorithm-CPP/README.md similarity index 100% rename from README.md rename to Algorithm-CPP/README.md diff --git a/Util.cpp b/Algorithm-CPP/Util.cpp similarity index 100% rename from Util.cpp rename to Algorithm-CPP/Util.cpp diff --git a/Util.h b/Algorithm-CPP/Util.h similarity index 100% rename from Util.h rename to Algorithm-CPP/Util.h diff --git a/Algorithm-Java-Backup/.DS_Store b/Algorithm-Java-Backup/.DS_Store new file mode 100644 index 0000000..1efdda3 Binary files /dev/null and b/Algorithm-Java-Backup/.DS_Store differ diff --git a/Algorithm-Java/SpiralMatrix.html b/Algorithm-Java-Backup/SpiralMatrix.html similarity index 100% rename from Algorithm-Java/SpiralMatrix.html rename to Algorithm-Java-Backup/SpiralMatrix.html diff --git a/Algorithm-Java/build.xml b/Algorithm-Java-Backup/build.xml similarity index 100% rename from Algorithm-Java/build.xml rename to Algorithm-Java-Backup/build.xml diff --git a/Algorithm-Java/hs_err_pid19383.log b/Algorithm-Java-Backup/hs_err_pid19383.log similarity index 100% rename from Algorithm-Java/hs_err_pid19383.log rename to Algorithm-Java-Backup/hs_err_pid19383.log diff --git a/Algorithm-Java/manifest.mf b/Algorithm-Java-Backup/manifest.mf similarity index 100% rename from Algorithm-Java/manifest.mf rename to Algorithm-Java-Backup/manifest.mf diff --git a/Algorithm-Java/nbproject/build-impl.xml b/Algorithm-Java-Backup/nbproject/build-impl.xml similarity index 100% rename from Algorithm-Java/nbproject/build-impl.xml rename to Algorithm-Java-Backup/nbproject/build-impl.xml diff --git a/Algorithm-Java/nbproject/genfiles.properties b/Algorithm-Java-Backup/nbproject/genfiles.properties similarity index 100% rename from Algorithm-Java/nbproject/genfiles.properties rename to Algorithm-Java-Backup/nbproject/genfiles.properties diff --git a/Algorithm-Java/nbproject/project.properties b/Algorithm-Java-Backup/nbproject/project.properties similarity index 100% rename from Algorithm-Java/nbproject/project.properties rename to Algorithm-Java-Backup/nbproject/project.properties diff --git a/Algorithm-Java/nbproject/project.xml b/Algorithm-Java-Backup/nbproject/project.xml similarity index 100% rename from Algorithm-Java/nbproject/project.xml rename to Algorithm-Java-Backup/nbproject/project.xml diff --git a/Algorithm-Java-Backup/src/.DS_Store b/Algorithm-Java-Backup/src/.DS_Store new file mode 100644 index 0000000..3f67fe3 Binary files /dev/null and b/Algorithm-Java-Backup/src/.DS_Store differ diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/KMP.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/KMP.java new file mode 100644 index 0000000..4b23bbd --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/KMP.java @@ -0,0 +1,53 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.ArraysAndStrings; + +public class KMP { + + public int search(String text, String pattern) { + int count = 0, length = text.length(), p_length = pattern.length(), i = 0, pos = 0; + int[] tab = next(pattern); + while (i < length) { + if (text.charAt(i) == pattern.charAt(pos)) { + ++pos; + if (pos == p_length) { + ++count; + pos = 0; + } + } else { + if (pos > 0) { + pos = tab[pos - 1] - 1; + } + } + ++i; + } + return count; + } + + public int[] next(String pattern) { + int pos = 0, i = 1, length = pattern.length(); + int[] tab = new int[length]; + //tab[0] = -1; + while (i < length) { + if (pattern.charAt(i) == pattern.charAt(pos)) { + tab[i++] = ++pos; + } else { + if (pos > 0) { + --pos; + } else { + tab[i++] = pos; + } + } + } + return tab; + } + + public static void main(String[] args) { + String pattern = "ababdab"; + String text = "ababdabssababdab"; + KMP kmp = new KMP(); + int count = kmp.search(text, pattern); + System.out.println(count); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_1_IsUnique.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_1_IsUnique.java new file mode 100644 index 0000000..62bea2f --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_1_IsUnique.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_1_IsUnique { + + boolean isUnique(String text) { + int i, length = text.length(); + if (length > 0xff) { + return false; + } + boolean[] charset = new boolean[0xff]; + for (i = 0; i < length; i++) { + char ch = text.charAt(i); + if (charset[ch]) { + return false; + } else { + charset[ch] = true; + } + } + return true; + } + + boolean isUnique2(String text) { + int i, length = text.length(); + if (length > 0xff) { + return false; + } + int intchecker = 0; + for (i = 0; i < length; i++) { + char ch = text.charAt(i); + if (((1 << ch) & intchecker) > 0) { + return false; + } else { + intchecker |= (1 << ch); + } + } + return true; + } + + public static void main(String[] args) { + Q1_1_IsUnique q1 = new Q1_1_IsUnique(); + System.out.println(q1.isUnique2("abcda")); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_3_IsPermutation.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_3_IsPermutation.java new file mode 100644 index 0000000..56f6a05 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_3_IsPermutation.java @@ -0,0 +1,28 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_3_IsPermutation { + + boolean isPermutation(String text, String pattern) { + int i, length = text.length(); + if (length != pattern.length()) { + return false; + } + short[] charset = new short[0xff]; + for (i = 0; i < length; i++) { + ++charset[text.charAt(i)]; + } + for (i = 0; i < length; i++) { + --charset[text.charAt(i)]; + if (charset[text.charAt(i)] < 0) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_4_UrlEncode.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_4_UrlEncode.java new file mode 100644 index 0000000..c408308 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_4_UrlEncode.java @@ -0,0 +1,37 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_4_UrlEncode { + + void encode(char[] text, int length) { + int i, newlength = length, j; + for (i = 0; i < length; i++) { + char ch = text[i]; + if (ch == ' ') { + newlength += 2; + } + } + j = newlength - 1; + for (i = length - 1; i >= 0; --i) { + if (text[i] != ' ') { + text[j--] = text[i]; + } else { + text[j--] = '0'; + text[j--] = '2'; + text[j--] = '%'; + } + } + } + + public static void main(String[] args) { + char[] text = "abc def ".toCharArray(); + Q1_4_UrlEncode q1 = new Q1_4_UrlEncode(); + q1.encode(text, 7); + for (char c : text) { + System.out.print(c); + } + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_5_CompressText.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_5_CompressText.java new file mode 100644 index 0000000..4012cd9 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_5_CompressText.java @@ -0,0 +1,49 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_5_CompressText { + + String compress(String text) { + + int i, length = text.length(); + if (getLength(text) >= length) { + return text; + } + StringBuilder sb = new StringBuilder(); + int count = 1; + for (i = 1; i < length; i++) { + if (text.charAt(i) == text.charAt(i - 1)) { + ++count; + } else { + sb.append(text.charAt(i - 1)).append(count); + count = 1; + } + } + sb.append(text.charAt(i - 1)).append(count); + return sb.toString(); + } + + int getLength(String text) { + int size = 0; + int i, length = text.length(); + int count = 1; + for (i = 1; i < length; i++) { + if (text.charAt(i) == text.charAt(i - 1)) { + ++count; + } else { + size += 1 + String.valueOf(count).length(); + count = 1; + } + } + size += 1 + String.valueOf(count).length(); + return size; + } + + public static void main(String[] args) { + Q1_5_CompressText q1 = new Q1_5_CompressText(); + String encrypt = q1.compress("aaaahhhuuuu"); + System.out.println(encrypt); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_6_RotateMatrix.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_6_RotateMatrix.java new file mode 100644 index 0000000..73dc789 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_6_RotateMatrix.java @@ -0,0 +1,37 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_6_RotateMatrix { + + public void rotate(int[][] matrix) { + int edge = matrix.length, i, level; + for (level = 0; level < edge / 2; level++) { + for (i = 0; i < edge - 2 * level - 1; i++) { + int temp = matrix[level][i]; + matrix[level][level + i] = matrix[ edge - level - 1 - i][level]; + matrix[edge - level - 1 - i][level] = matrix[edge - 1 - level - i][level]; + matrix[edge - 1 - level - i][level] = matrix[edge - level - 1][edge - level - 1 - i]; + matrix[edge - level - 1][edge - level - 1 - i] = matrix[level + i][edge - level - 1]; + matrix[level + i][edge - level - 1] = temp; + } + } + } + + public static void main(String[] args) { + int[][] matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + new Q1_6_RotateMatrix().rotate(matrix); + int edge = matrix.length; + for (int i = 0; i < edge; i++) { + for (int j = 0; j < edge; j++) { + System.out.print(matrix[i][j]); + } + System.out.println(); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_7_SetZero.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_7_SetZero.java new file mode 100644 index 0000000..476272d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_7_SetZero.java @@ -0,0 +1,30 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_7_SetZero { + + void setZero(int[][] matrix) { + int col, row, height = matrix.length, width = matrix[0].length; + boolean[] col_list = new boolean[height], row_list = new boolean[width]; + for (col = 0; col < height; col++) { + for (row = 0; row < width; row++) { + if (matrix[col][row] == 0) { + col_list[col] = true; + row_list[row] = true; + } + } + } + for (col = 0; col < height; col++) { + for (row = 0; row < width; row++) { + if (col_list[col] || row_list[row]) { + matrix[col][row] = 0; + } + } + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_8_IsRotate.java b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_8_IsRotate.java new file mode 100644 index 0000000..42a14fb --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ArraysAndStrings/Q1_8_IsRotate.java @@ -0,0 +1,19 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.ArraysAndStrings; + +public class Q1_8_IsRotate { + + boolean isRotate(String text1, String text2) + { + return (text1+text1).contains(text2); + } + + public static void main(String[] args) { + Q1_8_IsRotate q1 = new Q1_8_IsRotate(); + boolean result = q1.isRotate("abc", "cab"); + System.out.println(result); + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_1_Add.java b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_1_Add.java new file mode 100644 index 0000000..12ed13a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_1_Add.java @@ -0,0 +1,23 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Hard; + +public class Q18_1_Add { + + public int add(int a, int b) { + if (b == 0) { + return a; + } + int addition = a ^ b; + int carry = (a & b) << 1; + return add(addition, carry); + } + + public static void main(String[] args) { + int a = 10; + int b = 200; + int add = new Q18_1_Add().add(a, b); + System.out.println(add); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_2_ShuffleCard.java b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_2_ShuffleCard.java new file mode 100644 index 0000000..5b1f18a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_2_ShuffleCard.java @@ -0,0 +1,20 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Hard; + +public class Q18_2_ShuffleCard { + + public void shuffle(int[] cards) { + int i, length = cards.length; + for (i = 0; i < length - 1; i++) { + int r = (int) (Math.random() * (length - i)) + i; + int temp = cards[r]; + cards[r] = cards[i]; + cards[i] = temp; + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_3_RandomInt.java b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_3_RandomInt.java new file mode 100644 index 0000000..136fc58 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_3_RandomInt.java @@ -0,0 +1,21 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Hard; + +public class Q18_3_RandomInt { + + public int[] generate(int[] original, int m) { + int[] subset = new int[m]; + int[] array = original.clone(); + for (int i = 0; i < m; i++) { + int j = i + (int) (Math.random() * (m - i)); + subset[i] = array[j]; + array[j] = array[i]; + } + return subset; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_4_Count2InN.java b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_4_Count2InN.java new file mode 100644 index 0000000..55509ea --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Hard/Q18_4_Count2InN.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Hard; +public class Q18_4_Count2InN { + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_1_RemoveDuplicate.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_1_RemoveDuplicate.java new file mode 100644 index 0000000..440dd58 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_1_RemoveDuplicate.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; +import java.util.HashSet; + +public class Q2_1_RemoveDuplicate { + + void removeDuplicate(LinkedListNode head) + { + LinkedListNode loop = head.Next, pre = head; + HashSet tab = new HashSet<>(); + while (loop != null) { + if (tab.contains(loop.Data)) { + pre.Next = loop.Next; + }else{ + tab.add(loop.Data); + pre = loop; + } + loop = loop.Next; + } + } + + void removeDuplicate2(LinkedListNode head) + { + LinkedListNode loop = head.Next, pre = head, runner = head; + while (loop != null) { + runner = loop.Next; + pre = loop; + while (runner!= null) { + if (runner.Data == loop.Data) { + pre.Next = runner.Next; + }else{ + pre = runner; + } + runner = runner.Next; + } + loop = loop.Next; + } + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList4(); + //new Q2_1_RemoveDuplicate().removeDuplicate(head); + new Q2_1_RemoveDuplicate().removeDuplicate2(head); + head.print(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_2_KthLastNode.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_2_KthLastNode.java new file mode 100644 index 0000000..c972047 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_2_KthLastNode.java @@ -0,0 +1,69 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; + +public class Q2_2_KthLastNode { + + LinkedListNode getKthLastNode3(LinkedListNode head, int k) { + LinkedListNode left = head, right = head; + while (k-- > 0) { + right = right.Next; + } + while (right != null) { + left = left.Next; + right = right.Next; + } + return left; + } + static int count = 1; + + LinkedListNode getKthLastNode2(LinkedListNode head, int k) { + if (head == null) { + return null; + } + LinkedListNode node = getKthLastNode2(head.Next, k); + if (count <= k) { + ++count; + return head; + } + return node; + } + + LinkedListNode getKthLastNode(LinkedListNode head, Wrapper wr, int k) { + if (head == null) { + return null; + } + if (wr == null) { + wr = new Wrapper(1); + } + LinkedListNode node = getKthLastNode(head.Next, wr, k); + if (wr.count <= k) { + ++wr.count; + return head; + } + return node; + } + + class Wrapper { + + int count; + + public Wrapper(int _count) { + this.count = _count; + } + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList2(); + Q2_2_KthLastNode q2 = new Q2_2_KthLastNode(); + LinkedListNode node1 = q2.getKthLastNode(head, null, 2); + System.out.println(node1.Data); + LinkedListNode node2 = q2.getKthLastNode2(head, 2); + System.out.println(node2.Data); + LinkedListNode node3 = q2.getKthLastNode3(head, 2); + System.out.println(node3.Data); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_3_DeleteNode.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_3_DeleteNode.java new file mode 100644 index 0000000..dc11725 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_3_DeleteNode.java @@ -0,0 +1,24 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; + +public class Q2_3_DeleteNode { + + void delete(LinkedListNode node) + { + if (node.Next == null) { + System.out.println("No ways"); + //throw new Exception("UnSupported"); + throw new RuntimeException("UnSupported"); + }else{ + node.Data = node.Next.Data; + node.Next = node.Next.Next; + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_4_PartitionList.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_4_PartitionList.java new file mode 100644 index 0000000..c3e3d6e --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_4_PartitionList.java @@ -0,0 +1,90 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; + +public class Q2_4_PartitionList { + + LinkedListNode partition2(LinkedListNode head, int pivot) { + LinkedListNode Left = null, Right = null, cur = head, next = cur.Next; + while (cur != null) { + next = cur.Next; + int val = cur.Data; + if (val <= pivot) { + if (Left == null) { + Left = cur; + Left.Next = null; + } else { + cur.Next = Left; + Left = cur; + } + } else { + if (Right == null) { + Right = cur; + Right.Next = null; + } else { + cur.Next = Right; + Right = cur; + } + } + cur = next; + } + LinkedListNode Connecter = Left; + while (Connecter.Next != null) { + Connecter = Connecter.Next; + } + System.out.println("Pivot:" + Connecter.Data); + Connecter.Next = Right; + return Left; + } + + LinkedListNode partition1(LinkedListNode head, int pivot) { + LinkedListNode LeftStart = null, LeftEnd = null, RightStart = null, RightEnd = null, cur = head, next = cur.Next; + while (cur != null) { + next = cur.Next; + int val = cur.Data; + if (val <= pivot) { + if (LeftStart == null || LeftEnd == null) { + LeftStart = cur; + LeftEnd = cur; + } else { + LeftEnd.Next = cur; + LeftEnd = cur; + } + } else { + if (RightStart == null || RightEnd == null) { + RightStart = cur; + RightEnd = cur; + } else { + cur.Next = RightStart; + RightStart = cur; + } + } + cur = next; + } + if (RightEnd != null) { + RightEnd.Next = null; + } + if (LeftEnd != null) { + LeftEnd.Next = RightStart; + } + if (LeftStart != null) { + return LeftStart; + } else { + return RightStart; + } + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList5(); + head.print(); + + Q2_4_PartitionList q24 = new Q2_4_PartitionList(); + //LinkedListNode head1 = q24.partition1(head, 4); + //head1.print(); + LinkedListNode head2 = q24.partition2(head, 3); + head2.print(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_5_Addition.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_5_Addition.java new file mode 100644 index 0000000..c6e61e7 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_5_Addition.java @@ -0,0 +1,90 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; + +public class Q2_5_Addition { + + public LinkedListNode add2(LinkedListNode left, LinkedListNode right, int carry) { + int sum = carry; + if (left != null) { + sum += left.Data; + } + if (right != null) { + sum += right.Data; + } + int digit = sum % 10; + int next_carry = sum / 10; + LinkedListNode node = new LinkedListNode<>(digit); + if (next_carry > 0 || left != null || right != null) { + LinkedListNode next = add2(left.Next, right.Next, next_carry); + node.Next = next; + } + return node; + } + + public LinkedListNode add1(LinkedListNode left, LinkedListNode right) { + int l_length = left.getLength(); + int r_length = right.getLength(); + if (l_length >= r_length) { + int count = l_length - r_length; + right = padEmplty(right, count); + } else { + int count = r_length - l_length; + left = padEmplty(left, count); + } + Wrapper wr = addHelper(left, right); + if (wr.carry > 0) { + LinkedListNode node = new LinkedListNode<>(wr.carry); + node.Next = wr.node; + return node; + } else { + return wr.node; + } + } + + private Wrapper addHelper(LinkedListNode left, LinkedListNode right) { + if (left == null || right == null) { + return new Wrapper(null, 0); + } + Wrapper wr = addHelper(left.Next, right.Next); + int sum = left.Data + right.Data + wr.carry; + int digit = sum % 10; + int carry = sum / 10; + LinkedListNode node = new LinkedListNode<>(digit); + node.Next = wr.node; + return new Wrapper(node, carry); + } + + class Wrapper { + + int carry; + LinkedListNode node = null; + + public Wrapper(LinkedListNode _node, int _carry) { + this.node = _node; + this.carry = _carry; + } + } + + private LinkedListNode padEmplty(LinkedListNode head, int count) { + while (count-- > 0) { + LinkedListNode node = new LinkedListNode<>(0); + node.Next = head; + head = node; + } + return head; + } + + public static void main(String[] args) { + Q2_5_Addition q25 = new Q2_5_Addition(); + LinkedListNode left = LinkedListNode.getSampleLinkedList2(); + LinkedListNode right = LinkedListNode.getSampleLinkedList2(); + LinkedListNode head1 = q25.add1(left, right); + head1.print(); + LinkedListNode head2 = q25.add2(left, right, 0); + head2.print(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_6_FindBeginning.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_6_FindBeginning.java new file mode 100644 index 0000000..c88b1a4 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_6_FindBeginning.java @@ -0,0 +1,33 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; + +public class Q2_6_FindBeginning { + + LinkedListNode findBegin(LinkedListNode head) { + LinkedListNode fast = head, slow = head; + do { + if (fast == null || slow == null || fast.Next == null) { + System.out.println("No Loop!!!"); + return null; + } + fast = fast.Next.Next; + slow = slow.Next; + } while (fast != slow); + slow = head; + while (slow != fast) { + slow = slow.Next; + fast = fast.Next; + } + return fast; + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList6(); + LinkedListNode begin = new Q2_6_FindBeginning().findBegin(head); + System.out.println(begin.Data); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_7_IsPalindrome.java b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_7_IsPalindrome.java new file mode 100644 index 0000000..293d700 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/LinkedLists/Q2_7_IsPalindrome.java @@ -0,0 +1,73 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 2, 2013 + */ +package CareerCup.LinkedLists; + +import Util.LinkedListNode; +import java.util.Stack; + +public class Q2_7_IsPalindrome { + + boolean isPalindrome2(LinkedListNode head) { + Stack stack = new Stack<>(); + LinkedListNode fast = head, slow = head; + while (fast != null && fast.Next != null) { + stack.push(slow.Data); + slow = slow.Next; + fast = fast.Next.Next; + } + if (fast != null) { + slow = slow.Next; + } + while (!stack.isEmpty()) { + if (stack.pop() != slow.Data) { + return false; + } + slow = slow.Next; + } + return true; + } + + boolean isPalindrome(LinkedListNode head) { + int length = head.getLength(); + Wrapper wr = isPalindrome(head, length); + return wr.match; + } + + Wrapper isPalindrome(LinkedListNode head, int length) { + if (length == 2) { + return new Wrapper(head.Next.Next, head.Data == head.Next.Data); + } else if (length == 1) { + return new Wrapper(head.Next, true); + } else if (length == 0) { + return new Wrapper(head, true); + } + Wrapper wr = isPalindrome(head.Next, length - 2); + if (!wr.match || wr.node == null) { + return wr; + } + wr.match = head.Data == wr.node.Data; + wr.node = wr.node.Next; + return wr; + } + + class Wrapper { + + LinkedListNode node; + boolean match; + + public Wrapper(LinkedListNode _node, boolean _match) { + this.match = _match; + this.node = _node; + } + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList7(); + Q2_7_IsPalindrome q27 = new Q2_7_IsPalindrome(); + boolean result = q27.isPalindrome(head); + System.out.println(result); + boolean result2 = q27.isPalindrome2(head); + System.out.println(result2); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_3_Line/Line.java b/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_3_Line/Line.java new file mode 100644 index 0000000..964087c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_3_Line/Line.java @@ -0,0 +1,68 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.MathematicsAndProbability.Q7_3_Line; + +import java.util.HashMap; +import sun.net.www.content.audio.x_aiff; + +public class Line { + + final static double epsilon = 0.00001; + public double slope; + public double yintercept; + public boolean infinite_slope; + + public Line(double _slope, double _yintercept) { + this.yintercept = _yintercept; + this.slope = _slope; + //y = slope * x + yintercept + } + + public Line(Point p1, Point p2) { + if (Math.abs(p2.x - p1.x) > epsilon) { + this.slope = (p2.y - p1.y) / (p2.x - p1.x); + this.infinite_slope = false; + } else { + this.infinite_slope = true; + } + if (infinite_slope) { + this.yintercept = p1.x; + } else { + this.yintercept = p1.y - slope * p1.x; + } + + } + + @Override + public int hashCode() { + //return super.hashCode(); + return (int) (100 * slope) * (int) (yintercept * 100) * (infinite_slope ? 1 : -1); + } + + public boolean isIntersect(Line another) { + return Math.abs(this.slope - another.slope) > epsilon + || Math.abs(this.yintercept - another.yintercept) < epsilon; + } + + @Override + public boolean equals(Object obj) { + //return super.equals(obj); + Line another = (Line) obj; + return Math.abs(this.slope - another.slope) < epsilon + && Math.abs(this.yintercept - another.yintercept) < epsilon + && this.infinite_slope == another.infinite_slope; + } + + public static void main(String[] args) { + Line l1 = new Line(new Point(0, 0), new Point(1, 1)); + Line l2 = new Line(new Point(0, 0), new Point(-1, -1)); + Line l3 = new Line(new Point(0, 0), new Point(2, 2)); + Line l4 = new Line(new Point(2, 2), new Point(1, 1)); + HashMap count = new HashMap<>(); + count.put(l1, 4); + count.put(l1, 3); + count.put(l1, 2); + count.put(l1, 1); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_3_Line/Point.java b/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_3_Line/Point.java new file mode 100644 index 0000000..3dd8882 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_3_Line/Point.java @@ -0,0 +1,18 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.MathematicsAndProbability.Q7_3_Line; + +public class Point { + + public double x; + public double y; + + public Point(double _x, double _y) { + this.x = _x; + this.y = _y; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_7_UnglyNumber/UnglyNumber.java b/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_7_UnglyNumber/UnglyNumber.java new file mode 100644 index 0000000..472a41c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/MathematicsAndProbability/Q7_7_UnglyNumber/UnglyNumber.java @@ -0,0 +1,43 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.MathematicsAndProbability.Q7_7_UnglyNumber; + +import java.util.LinkedList; +import java.util.Queue; + +public class UnglyNumber { + + public int getKthUnglyNumber(int k) { + Queue s3 = new LinkedList<>(); + Queue s5 = new LinkedList<>(); + Queue s7 = new LinkedList<>(); + int val = 1; + s3.add(1); + while (--k > 0) { + int v3 = s3.isEmpty() ? Integer.MAX_VALUE : s3.peek(); + int v5 = s5.isEmpty() ? Integer.MAX_VALUE : s5.peek(); + int v7 = s7.isEmpty() ? Integer.MAX_VALUE : s7.peek(); + val = Math.min(v7, Math.min(v3, v5)); + if (val == v3) { + s3.poll(); + s3.add(val * 3); + s5.add(val * 5); + s7.add(val * 7); + } else if (val == v5) { + s5.poll(); + s5.add(val * 5); + s7.add(val * 7); + } else if (val == v7) { + s7.poll(); + s7.add(val * 7); + } + System.out.println(val); + } + return val; + } + + public static void main(String[] args) { + new UnglyNumber().getKthUnglyNumber(100); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_10_EncodeXML.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_10_EncodeXML.java new file mode 100644 index 0000000..9b1c107 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_10_EncodeXML.java @@ -0,0 +1,14 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Moderate; + +public class Q17_10_EncodeXML { + + public void encode(StringBuffer sb) { + + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_11_Random7.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_11_Random7.java new file mode 100644 index 0000000..f7815c0 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_11_Random7.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Moderate; +public class Q17_11_Random7 { + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_12_PairToSum.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_12_PairToSum.java new file mode 100644 index 0000000..5df3eab --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_12_PairToSum.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Moderate; +public class Q17_12_PairToSum { + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_13_BinaryTree2LinkedList.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_13_BinaryTree2LinkedList.java new file mode 100644 index 0000000..55d76f1 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_13_BinaryTree2LinkedList.java @@ -0,0 +1,10 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Moderate; + +public class Q17_13_BinaryTree2LinkedList { + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_14_ParseWord.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_14_ParseWord.java new file mode 100644 index 0000000..bdec870 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_14_ParseWord.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Moderate; +public class Q17_14_ParseWord { + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_1_Swap.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_1_Swap.java new file mode 100644 index 0000000..6329038 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_1_Swap.java @@ -0,0 +1,30 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.Moderate; + +public class Q17_1_Swap { + + void swap(int a, int b) { + //diff = a - b + a = a - b; + b = a + b; + a = b - a; + System.out.println("a:" + a); + System.out.println("b:" + b); + } + + void swap2(int a, int b) { + a = a ^ b; + b = a ^ b; + a = a ^ b; + System.out.println("a:" + a); + System.out.println("b:" + b); + } + + public static void main(String[] args) { + Q17_1_Swap swap = new Q17_1_Swap(); + swap.swap(1, 3); + swap.swap2(3, 4); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_2_TicTacToe.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_2_TicTacToe.java new file mode 100644 index 0000000..195a070 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_2_TicTacToe.java @@ -0,0 +1,71 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.Moderate; + +public class Q17_2_TicTacToe { + + enum Piece { + + X, O, Empty + } + + public Piece hasWon(Piece[][] board) { + int n = board.length; + int col, row; + //Check row + for (col = 0; col < n; col++) { + if (board[col][0] == Piece.Empty) { + break; + } + for (row = 1; row < n; row++) { + if (board[col][row] == Piece.Empty || board[col][row] != board[col][row - 1]) { + break; + } + if (row == n - 1) { + return board[col][row]; + } + } + } + //check col + for (row = 0; row < n; row++) { + if (board[col][row] == Piece.Empty) { + break; + } + for (col = 1; col < n; col++) { + if (board[col][row] == Piece.Empty || board[col][row] != board[col - 1][row]) { + break; + } + } + if (col == n - 1) { + return board[col][row]; + } + } + //diagonal + if (board[0][0] != Piece.Empty) { + for (col = 1; col < n; col++) { + if (board[col][col] == Piece.Empty || board[col][col] != board[col - 1][col - 1]) { + break; + } + if (col == n - 1) { + return board[col][col]; + } + } + } + //reverse diagonal + if (board[0][n - 1] != Piece.Empty) { + for (col = 1; col < n; col++) { + if (board[col][n - 1 - col] == Piece.Empty || board[col][n - 1 - col] != board[col - 1][n - col]) { + break; + } + if (col == n - 1) { + return board[col][n - 1 - col]; + } + } + } + return Piece.Empty; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_3_ZeroInFactorial.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_3_ZeroInFactorial.java new file mode 100644 index 0000000..d0e12f6 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_3_ZeroInFactorial.java @@ -0,0 +1,41 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.Moderate; + +public class Q17_3_ZeroInFactorial { + + public int factorOf5(int n) { + int count = 0; + while (n % 5 == 0) { + ++count; + n /= 5; + } + return count; + } + + public int countZero(int num) { + int count = 0; + for (int i = 2; i <= num; i++) { + count += factorOf5(i); + } + return count; + } + + public int countZero2(int num) { + int count = 0; + for (int i = 5; num / i > 0; i *= 5) { + count += num / i; + } + return count; + } + + public static void main(String[] args) { + int num = 19; + Q17_3_ZeroInFactorial q17 = new Q17_3_ZeroInFactorial(); + int ways = q17.countZero(num); + System.out.println(ways); + int ways2 = q17.countZero2(num); + System.out.println(ways2); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_4_Max.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_4_Max.java new file mode 100644 index 0000000..0a86326 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_4_Max.java @@ -0,0 +1,38 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 29, 2012 + */ +package CareerCup.Moderate; + +public class Q17_4_Max { + + public int max(int a, int b) { + int k = positive(a - b); + int q = flip(k); + return k * b + q * a; + } + + public int flip(int n) { + return n ^ 0x1; + } + + public int positive(int n) { + return (n >> 31) & 0x1; + } + + public int max2(int a, int b) { + int sa = positive(a); + int sb = positive(b); + int sc = positive(a - b); + int use_sign_a = sa ^ sb; + int use_sign_c = flip(use_sign_a); + int k = use_sign_a * sa + use_sign_c * sc; + int q = flip(k); + return k * b + q * a; + } + + public static void main(String[] args) { + Q17_4_Max q174 = new Q17_4_Max(); + System.out.println(q174.max(-3, 9)); + System.out.println(q174.max2(3, 5)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_5_MasterMind.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_5_MasterMind.java new file mode 100644 index 0000000..c2c9c0f --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_5_MasterMind.java @@ -0,0 +1,62 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 29, 2012 + */ +package CareerCup.Moderate; + +public class Q17_5_MasterMind { + + public class Result { + + public int hits = 0; + public int pseudo_hits = 0; + + @Override + public String toString() { + return "Hits:" + hits + " PseudoHits:" + pseudo_hits; + } + } + + public int code(char c) { + switch (c) { + case 'B': + return 0; + case 'G': + return 1; + case 'R': + return 2; + case 'Y': + return 3; + default: + return -1; + } + } + final short NUM_COLORS = 4; + + public Result estimate(String guess, String solution) { + if (guess.length() != solution.length()) { + return null; + } + Result r = new Result(); + short frequency[] = new short[NUM_COLORS]; + int i, length = solution.length(); + for (i = 0; i < length; i++) { + if (guess.charAt(i) == solution.charAt(i)) { + ++r.hits; + } else { + ++frequency[code(solution.charAt(i))]; + } + } + for (i = 0; i < length; i++) { + if (guess.charAt(i) != solution.charAt(i) + && frequency[code(guess.charAt(i))] > 0 + && code(guess.charAt(i)) >= 0) { + --frequency[code(guess.charAt(i))]; + ++r.pseudo_hits; + } + } + return r; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_6_FindMNToBeSorted.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_6_FindMNToBeSorted.java new file mode 100644 index 0000000..e98f9bf --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_6_FindMNToBeSorted.java @@ -0,0 +1,75 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 29, 2012 + */ +package CareerCup.Moderate; + +public class Q17_6_FindMNToBeSorted { + + public int findEndOfLeftSubsequence(int[] arr) { + int i, length = arr.length; + for (i = 1; i < length; i++) { + if (arr[i] < arr[i - 1]) { + break; + } + } + return i - 1; + } + + public int findStartOfRightSubsequence(int[] arr) { + int i, length = arr.length; + for (i = length - 2; i >= 0; i--) { + if (arr[i] > arr[i + 1]) { + break; + } + } + return i + 1; + } + + public int shrinkLeft(int[] arr, int min_index, int start) { + int comp = arr[min_index], i; + for (i = start - 1; i >= 0; --i) { + if (arr[i] <= comp) { + return i + 1; + } + } + return 0; + } + + public int shrinkRight(int[] arr, int max_index, int start) { + int comp = arr[max_index], i, length = arr.length; + for (i = start + 1; i < length - 1; i++) { + if (arr[i] >= comp) { + return i - 1; + } + } + return length - 1; + } + + public void findMN(int[] arr) { + int length = arr.length, i; + int end_left = findEndOfLeftSubsequence(arr); + int start_right = findStartOfRightSubsequence(arr); + + int max_index = start_right - 1; + int min_index = end_left + 1; + if (min_index == length || max_index < 0) { + return; + } + for (i = end_left; i <= start_right; i++) { + if (arr[i] > arr[max_index]) { + max_index = i; + } + if (arr[i] < arr[min_index]) { + min_index = i; + } + } + int m = shrinkLeft(arr, min_index, end_left); + int n = shrinkRight(arr, max_index, start_right); + System.out.println("m:" + m + " n:" + n); + } + + public static void main(String[] args) { + int[] arr = {1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19}; + new Q17_6_FindMNToBeSorted().findMN(arr); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_7_ConvertToEnglish.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_7_ConvertToEnglish.java new file mode 100644 index 0000000..25d7030 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_7_ConvertToEnglish.java @@ -0,0 +1,57 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 29, 2012 + */ +package CareerCup.Moderate; + +public class Q17_7_ConvertToEnglish { + + final String[] bigs = {"Thousand", "Million", "Billion"}; + final String[] digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; + final String[] teens = {"Eleven", "Twelve", "Thirsteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; + final String[] tens = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninty"}; + + public String convert(int num) { + StringBuilder sb = new StringBuilder(); + boolean negative = false; + if (num < 0) { + negative = true; + num = -num; + } else if (num == 0) { + return "Zero"; + } + int count = -1; + while (num > 0) { + if (count >= 0) { + sb.insert(0, bigs[count]).insert(0, " ");; + } + sb.insert(0, convert100(num % 1000)).insert(0, " "); + num /= 1000; + ++count; + } + if (negative) { + sb.insert(0, "Negative "); + } + return sb.toString(); + } + + private String convert100(int num) { + StringBuilder sb = new StringBuilder(); + if (num >= 100) { + sb.append(digits[ num / 100 - 1]).append(" Hundred "); + num %= 100; + } + if (num > 19) { + sb.append(tens[num / 10 - 1]).append(" ").append(digits[num % 10 - 1]).append(" "); + } else if (num >= 11) { + sb.append(teens[num % 10 - 1]).append(" "); + } else { + sb.append(digits[num % 10 - 1]).append(" "); + } + return sb.toString(); + } + + public static void main(String[] args) { + Q17_7_ConvertToEnglish q17 = new Q17_7_ConvertToEnglish(); + System.out.println(q17.convert(3111234)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_8_LargestSum.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_8_LargestSum.java new file mode 100644 index 0000000..384a2e9 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_8_LargestSum.java @@ -0,0 +1,33 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 29, 2012 + */ +package CareerCup.Moderate; + +public class Q17_8_LargestSum { + + public int sum(int[] arr) { + int max = arr[0], sum = arr[0], i, length = arr.length; + for (i = 1; i < length; i++) { + sum += arr[i]; + if (sum > max) { + max = sum; + } else if (sum < 0) { + sum = 0; + } + } + if (max <= 0) { + for (i = 0; i < length; i++) { + if (arr[i] > max) { + max = arr[i]; + } + } + } + return max; + } + + public static void main(String[] args) { + int[] arr = {1, 2, 3, -2, -1, 9, -100}; + int sum = new Q17_8_LargestSum().sum(arr); + System.out.println(sum); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_9_FrequencyWordInBook.java b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_9_FrequencyWordInBook.java new file mode 100644 index 0000000..0d59633 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/Moderate/Q17_9_FrequencyWordInBook.java @@ -0,0 +1,7 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.Moderate; +public class Q17_9_FrequencyWordInBook { + +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_10_HashTable/Entry.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_10_HashTable/Entry.java new file mode 100644 index 0000000..47d73bf --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_10_HashTable/Entry.java @@ -0,0 +1,72 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_10_HashTable; + +public class Entry { + + private V Value; + + public V getValue() { + return Value; + } + + public void setValue(V Value) { + this.Value = Value; + } + private K Key; + + public K getKey() { + return Key; + } + + public void setKey(K Key) { + this.Key = Key; + } + private Entry Next; + + public Entry getNext() { + return Next; + } + + public void setNext(Entry Next) { + this.Next = Next; + } + + public Entry(K _k, V _v) { + this.Key = _k; + this.Value = _v; + this.Next = null; + } + + public void addEntry(Entry _e) { + Entry runner = this; + if (runner != null && runner.getKey() == _e.Key) { + runner.setValue(_e.Value); + return; + } + while (runner.Next != null) { + runner = runner.Next; + if (runner != null && runner.getKey() == _e.Key) { + runner.setValue(_e.Value); + return; + } + } + runner.Next = _e; + } + + public void deleteEntry(K key) { + Entry runner = this; + while (runner != null) { + Entry next_entry = runner.getNext(); + if (next_entry != null && next_entry.getKey() == key) { + runner.setNext(next_entry.getNext()); + return; + } + runner = next_entry; + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_10_HashTable/HashTable.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_10_HashTable/HashTable.java new file mode 100644 index 0000000..1907e9f --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_10_HashTable/HashTable.java @@ -0,0 +1,66 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_10_HashTable; + +public class HashTable { + + public int Capacity = 1000; + public Entry[] array; + + public HashTable() { + array = new Entry[Capacity]; + } + + public HashTable(int _capacity) { + this.Capacity = _capacity; + array = new Entry[Capacity]; + } + + public synchronized void put(K key, V value) { + int hash = key.hashCode() % Capacity; + Entry new_entry = new Entry(key, value); + if (array[hash] == null) { + array[hash] = new_entry; + } else { + array[hash].addEntry(new_entry); + } + } + + public synchronized V get(K key) { + int hash = key.hashCode() % Capacity; + Entry e = array[hash]; + while (e != null && !e.getKey().equals(key)) { + e = e.getNext(); + } + if (e == null) { + return null; + } else { + return e.getValue(); + } + } + + public synchronized void delete(K key) { + int hash = key.hashCode() % Capacity; + if (array[hash] != null && array[hash].getKey() == key) { + array[hash] = array[hash].getNext(); + } else { + array[hash].deleteEntry(key); + } + } + + public static void main(String[] args) { + HashTable ht = new HashTable<>(10); + ht.put(1, "xxx"); + ht.put(2, "yyy"); + ht.put(3, "zzz"); + ht.put(4, "qqq"); + System.out.println(ht.get(1)); + System.out.println(ht.get(2)); + //ht.delete(1); + System.out.println(ht.get(1)); + //ht.delete(2); + ht.put(2, "ZSQ"); + System.out.println(ht.get(2)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Card.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Card.java new file mode 100644 index 0000000..f41776a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Card.java @@ -0,0 +1,26 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_1_DeckCard; + +public abstract class Card { + + int face_value; + Suit suit; + boolean avaiable; + + public Card(int _val, Suit _suit) { + this.face_value = _val; + this.suit = _suit; + avaiable = true; + } + + public void markAvailable(boolean isAvailable) { + this.avaiable = isAvailable; + } + + public abstract int value(); + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Deck.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Deck.java new file mode 100644 index 0000000..da78730 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Deck.java @@ -0,0 +1,60 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_1_DeckCard; + +import java.util.ArrayList; +import java.util.Random; + +public class Deck { + + public ArrayList cards; + private int dealt_num = 0; + + public Deck() { + this.cards = new ArrayList<>(); + } + + public int remainingCard() { + return cards.size() - dealt_num; + } + + public T[] dealtHand(int num) { + if (num > remainingCard()) { + return null; + } + T[] card_hand = (T[]) new Card[num]; + for (int i = 0; i < num; i++) { + T card = dealtCard(); + if (card != null) { + card_hand[i] = card; + } + } + return card_hand; + } + + public T dealtCard() { + if (remainingCard() == 0) { + return null; + } + T card = cards.get(dealt_num); + card.markAvailable(false); + ++dealt_num; + return card; + } + + public void shuffle() { + Random r = new Random(System.currentTimeMillis()); + int i, size = cards.size(), j; + for (i = 0; i < size; i++) { + j = r.nextInt(size); + T card1 = cards.get(i); + T card2 = cards.get(j); + cards.set(i, card2); + cards.set(j, card1); + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Hand.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Hand.java new file mode 100644 index 0000000..223706e --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Hand.java @@ -0,0 +1,30 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_1_DeckCard; + +import java.util.ArrayList; + +public class Hand { + + public ArrayList cards_onhand; + + public Hand() { + cards_onhand = new ArrayList<>(); + } + + public int value() { + int val = 0; + for (T t : cards_onhand) { + val += t.value(); + } + return val; + } + + public void add(T card) { + cards_onhand.add(card); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Suit.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Suit.java new file mode 100644 index 0000000..ae5202c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_1_DeckCard/Suit.java @@ -0,0 +1,36 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_1_DeckCard; + +public enum Suit { + + Club(0), + Diamond(1), + Heart(2), + Spade(3); + int i; + + Suit(int _i) { + this.i = _i; + } + + public int getValue() { + return i; + } + + public static Suit getSuitFromValue(int value) { + switch (value) { + case 0: + return Suit.Club; + case 1: + return Suit.Diamond; + case 2: + return Suit.Heart; + case 3: + return Suit.Spade; + default: + return null; + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Call.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Call.java new file mode 100644 index 0000000..d4043ce --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Call.java @@ -0,0 +1,27 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public class Call { + + public Rank rank; + public Caller caller; + public Employee handler; + + public Rank incrementRank() { + if (rank == Rank.Responder) { + rank = Rank.Manager; + } else if (rank == Rank.Manager) { + rank = Rank.Director; + } + return null; + } + + public void disconnect() { + System.out.println("Good Bye"); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/CallHandler.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/CallHandler.java new file mode 100644 index 0000000..b0e74e4 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/CallHandler.java @@ -0,0 +1,85 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class CallHandler { + + final int NUM_LEVEL = 3; + final int NUM_RESPONDENT = 10; + final int NUM_MANAGER = 5; + final int NUM_DIRECTOR = 1; + private static CallHandler inst; + ArrayList employees[]; + Queue callqueue[]; + + private CallHandler() { + int i; + employees = new ArrayList[NUM_LEVEL]; + for (i = 0; i < NUM_LEVEL; i++) { + employees[i] = new ArrayList<>(); + } + callqueue = new LinkedList[NUM_LEVEL]; + for (i = 0; i < NUM_LEVEL; i++) { + callqueue[i] = new LinkedList<>(); + } + for (i = 0; i < NUM_RESPONDENT; i++) { + employees[0].add(new Respondent()); + } + for (i = 0; i < NUM_MANAGER; i++) { + employees[1].add(new Manager()); + } + for (i = 0; i < NUM_DIRECTOR; i++) { + employees[2].add(new Director()); + } + } + + public static CallHandler getInstance() { + if (inst == null) { + inst = new CallHandler(); + } + return inst; + } + + public Employee getHandlerForCall(Call c) { + for (Rank i = c.rank; i != null; c.incrementRank()) { + ArrayList list = employees[i.getValue()]; + for (Employee employee : list) { + if (employee.isFree()) { + //employee.receiveCall(c); + return employee; + } + } + } + return null; + } + + public void dispatchCall(Call c) { + Employee employee = getHandlerForCall(c); + if (employee != null) { + employee.receiveCall(c); + c.handler = employee; + } else { + System.out.println("No Available employee"); + callqueue[c.rank.getValue()].add(c); + } + } + + public boolean assignCall(Employee e) { + for (int r = e.rank.getValue(); r >= 0; --r) { + Queue queue = callqueue[r]; + if (queue.peek() != null) { + e.receiveCall(queue.poll()); + return true; + } + } + return false; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Caller.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Caller.java new file mode 100644 index 0000000..0a70d40 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Caller.java @@ -0,0 +1,16 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public class Caller { + + public String name; + + public Caller(String _name) { + this.name = _name; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Director.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Director.java new file mode 100644 index 0000000..86b678e --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Director.java @@ -0,0 +1,14 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public class Director extends Employee { + + public Director() { + this.rank = Rank.Director; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Employee.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Employee.java new file mode 100644 index 0000000..959e102 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Employee.java @@ -0,0 +1,44 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public abstract class Employee { + + public Call current_call; + Rank rank; + + public void receiveCall(Call c) { + current_call = c; + } + + public boolean isFree() { + return current_call == null; + } + + public void callComplete() { + if (current_call != null) { + current_call.disconnect(); + current_call = null; + } + assignNewCall(); + } + + public void assignNewCall() { + if (isFree()) { + CallHandler.getInstance().assignCall(this); + } + } + + public void escalateCall() { + if (current_call != null) { + current_call.incrementRank(); + CallHandler.getInstance().dispatchCall(current_call); + current_call = null; + } + assignNewCall(); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Manager.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Manager.java new file mode 100644 index 0000000..87cf539 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Manager.java @@ -0,0 +1,14 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public class Manager extends Employee { + + public Manager() { + this.rank = Rank.Manager; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Rank.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Rank.java new file mode 100644 index 0000000..58e3122 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Rank.java @@ -0,0 +1,20 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public enum Rank { + + Responder(0), + Manager(1), + Director(2); + private int val; + + private Rank(int _val) { + this.val = _val; + } + + public int getValue() { + return val; + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Respondent.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Respondent.java new file mode 100644 index 0000000..3cbc4e2 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_2_CallCenter/Respondent.java @@ -0,0 +1,14 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_2_CallCenter; + +public class Respondent extends Employee { + + public Respondent() { + rank = Rank.Responder; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/CD.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/CD.java new file mode 100644 index 0000000..ec997d8 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/CD.java @@ -0,0 +1,12 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +public class CD { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/CDPlayer.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/CDPlayer.java new file mode 100644 index 0000000..d7ef4e8 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/CDPlayer.java @@ -0,0 +1,17 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +public class CDPlayer { + + CD cd; + PlayList playlist; + + + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/JukeBox.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/JukeBox.java new file mode 100644 index 0000000..541c4c9 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/JukeBox.java @@ -0,0 +1,19 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +import java.util.Set; + +public class JukeBox { + + User user; + CDPlayer player; + Set cds; + SongSelector cs; + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/PlayList.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/PlayList.java new file mode 100644 index 0000000..3c65bed --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/PlayList.java @@ -0,0 +1,24 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +import java.util.LinkedList; +import java.util.Queue; + +public class PlayList { + + private Queue playlist; + Song cur; + + public PlayList(Queue _playlist) { + this.playlist = new LinkedList<>(); + } + + public void playNext() { + cur = playlist.poll(); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/Song.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/Song.java new file mode 100644 index 0000000..f2b7384 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/Song.java @@ -0,0 +1,14 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +public class Song { + + public String SongName; + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/SongSelector.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/SongSelector.java new file mode 100644 index 0000000..318031d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/SongSelector.java @@ -0,0 +1,14 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +public class SongSelector { + + public Song cur_song; + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/User.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/User.java new file mode 100644 index 0000000..a958224 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_3_JukeBox/User.java @@ -0,0 +1,19 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_3_JukeBox; + +import java.math.BigInteger; + +public class User { + + BigInteger id; + String name; + + public User(String _name) { + this.name = _name; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Bus.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Bus.java new file mode 100644 index 0000000..4990e03 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Bus.java @@ -0,0 +1,18 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +public class Bus extends Vehicle { + + public Bus() { + super(); + this.size = VehicleSize.Large; + this.SpotOccupy = 4; + } + + @Override + public boolean canfit(ParkingSpot parkingSpot) { + return parkingSpot.SpotSize == VehicleSize.Large; + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Car.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Car.java new file mode 100644 index 0000000..81bbe99 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Car.java @@ -0,0 +1,21 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +public class Car extends Vehicle { + + public Car() { + super(); + this.size = VehicleSize.Compact; + this.SpotOccupy = 2; + } + + @Override + public boolean canfit(ParkingSpot parkingSpot) { + return parkingSpot.SpotSize == VehicleSize.Compact || parkingSpot.SpotSize == VehicleSize.Large; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Level.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Level.java new file mode 100644 index 0000000..f896275 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Level.java @@ -0,0 +1,79 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +public class Level { + + int numSpots; + int floor; + ParkingSpot[] parkingspots; + private static final int NUM_PER_ROW = 10; + private int availableSpot; + + public Level(int _num_sports, int _floor) { + this.floor = _floor; + this.numSpots = _num_sports; + parkingspots = new ParkingSpot[_num_sports]; + int large = _num_sports / 4; + int bike = _num_sports / 4; + int compact = _num_sports - large - bike; + for (int i = 0; i < _num_sports; i++) { + VehicleSize size = VehicleSize.Compact; + if (i < bike) { + size = VehicleSize.Motorcycle; + } else if (i < bike + large) { + size = VehicleSize.Large; + } + int row = i / NUM_PER_ROW; + parkingspots[i] = new ParkingSpot(size, i, row, _floor); + } + availableSpot = _num_sports; + } + + public boolean partVehicle(Vehicle v) { + if (availableSpot < v.SpotOccupy) { + return false; + } + int FindSpot = findAvailableSpot(v); + if (FindSpot < 0) { + return false; + } + return partStartingAtSpot(v, FindSpot); + } + + private boolean partStartingAtSpot(Vehicle v, int i) { + v.clearSpot(); + boolean success = true; + for (int j = i; j < v.SpotOccupy; j++) { + success &= parkingspots[i].partVehicle(v); + } + if (success) { + availableSpot -= v.SpotOccupy; + } + return success; + } + + private int findAvailableSpot(Vehicle v) { + int SpotNeed = v.SpotOccupy; + int LastRow = -1; + int SpotFind = 0; + for (int i = 0; i < numSpots; i++) { + ParkingSpot ps = parkingspots[i]; + if (LastRow != ps.getRow()) { + LastRow = ps.getRow(); + SpotFind = 0; + } + if (ps.canFitVehicle(v)) { + ++SpotFind; + } + if (SpotFind == SpotNeed) { + return i - (SpotNeed - 1); + } + } + return -1; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/ParkingLot.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/ParkingLot.java new file mode 100644 index 0000000..545da56 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/ParkingLot.java @@ -0,0 +1,26 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +public class ParkingLot { + + private Level[] levels; + private final int num_floor = 5; + + public ParkingLot() { + levels = new Level[num_floor]; + } + + public boolean partAtLot(Vehicle v) { + for (int i = 0; i < num_floor; i++) { + if (levels[i].partVehicle(v)) { + return true; + } + } + return false; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/ParkingSpot.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/ParkingSpot.java new file mode 100644 index 0000000..83f8c58 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/ParkingSpot.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +public class ParkingSpot { + + private Vehicle CurrentVehicle; + private int num, row; + public VehicleSize SpotSize; + int floor; + + public ParkingSpot(VehicleSize _size, int _num, int _row, int _floor) { + this.SpotSize = _size; + this.num = _num; + this.row = _row; + this.floor = _floor; + } + + public int getRow(){ + return row; + } + + public void removeVehicle() { + CurrentVehicle = null; + } + + private boolean isAvailable() { + return CurrentVehicle == null; + } + + public boolean canFitVehicle(Vehicle v) { + return isAvailable() && v.canfit(this); + } + + public boolean partVehicle(Vehicle v) { + if (!canFitVehicle(v)) { + return false; + } + CurrentVehicle = v; + v.partInSpot(this); + return true; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Vehicle.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Vehicle.java new file mode 100644 index 0000000..1cf4ac3 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/Vehicle.java @@ -0,0 +1,33 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +import java.util.ArrayList; + +public abstract class Vehicle { + + public VehicleSize size; + public int SpotOccupy; + public ArrayList ParkingSpots; + + public Vehicle() { + this.ParkingSpots = new ArrayList<>(); + } + + public void partInSpot(ParkingSpot ps) { + this.ParkingSpots.add(ps); + } + + public void clearSpot() { + for (ParkingSpot parkingSpot : ParkingSpots) { + parkingSpot.removeVehicle(); + } + this.ParkingSpots.clear(); + } + + public abstract boolean canfit(ParkingSpot parkingSpot); + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/VehicleSize.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/VehicleSize.java new file mode 100644 index 0000000..167ffa6 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_4_ParkingLot/VehicleSize.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_4_ParkingLot; + +public enum VehicleSize { + + Motorcycle, Compact, Large +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Book.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Book.java new file mode 100644 index 0000000..fdbea2d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Book.java @@ -0,0 +1,18 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_5_OnlineBookReader; + +public class Book { + + private int book_id; + private String detail; + + public Book(int _book_id, String _detail) { + this.book_id = _book_id; + this.detail = _detail; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Display.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Display.java new file mode 100644 index 0000000..fb9df1d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Display.java @@ -0,0 +1,20 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_5_OnlineBookReader; + +public class Display { + + private Book active_book; + private User active_user; + private long page_num; + + public Display(Book _book, User _user) { + this.active_book = _book; + this.active_user = _user; + page_num = 1; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Library.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Library.java new file mode 100644 index 0000000..21a1e54 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/Library.java @@ -0,0 +1,42 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_5_OnlineBookReader; + +import CareerCup.ObjectOrientedDesign.Q8_10_HashTable.HashTable; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Iterator; + +public class Library { + + private HashTable DB; + private static Library inst; + + private Library() { + DB = new HashTable<>(); + } + + public static Library getInstance() { + if (inst == null) { + inst = new Library(); + } + return inst; + } + + public void bulkAddBook(Dictionary list) { + Enumeration keys = list.keys(); + for (; keys.hasMoreElements();) { + int id = keys.nextElement(); + Book book = list.get(id); + DB.put(id, book); + } + } + + public Book find(int _book_id) { + return DB.get(_book_id); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/OnlineReaderSystem.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/OnlineReaderSystem.java new file mode 100644 index 0000000..ca8eaa7 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/OnlineReaderSystem.java @@ -0,0 +1,31 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_5_OnlineBookReader; + +import java.util.HashSet; + +public class OnlineReaderSystem { + + private Library lib; + private UserManager manager; + private HashSet displays; + private static OnlineReaderSystem inst; + + private OnlineReaderSystem() { + lib = Library.getInstance(); + manager = UserManager.getInstance(); + displays = new HashSet<>(); + } + + public Display read(User _user, Book _book) { + Display d = new Display(_book, _user); + if (!displays.contains(d)) { + displays.add(d); + } + return d; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/User.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/User.java new file mode 100644 index 0000000..7333a86 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/User.java @@ -0,0 +1,22 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_5_OnlineBookReader; + +import java.math.BigInteger; + +public class User { + + private BigInteger ID; + public String Name; + private short Type; + + public User(BigInteger _id, String _name, short _type) { + this.ID = _id; + this.Name = _name; + this.Type = _type; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/UserManager.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/UserManager.java new file mode 100644 index 0000000..273d34d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_5_OnlineBookReader/UserManager.java @@ -0,0 +1,40 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_5_OnlineBookReader; + +import CareerCup.ObjectOrientedDesign.Q8_10_HashTable.HashTable; +import java.math.BigInteger; + +public class UserManager { + + public HashTable DB; + private static UserManager inst; + + private UserManager() { + DB = new HashTable<>(); + entity = BigInteger.ONE; + } + + public static UserManager getInstance() { + if (inst == null) { + inst = new UserManager(); + } + return inst; + } + static BigInteger entity; + + public void addUser(String _name, short _type) { + entity = entity.add(BigInteger.ONE); + BigInteger id = entity; + User u = new User(id, _name, _type); + DB.put(id, u); + } + + public void removeUser(BigInteger _id) { + DB.delete(_id); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Edge.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Edge.java new file mode 100644 index 0000000..0dfe972 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Edge.java @@ -0,0 +1,26 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_6_Jigsaw; + +public class Edge { + + public EdgeType type; + public Piece parent; + + public boolean fitWith(Edge e) { + if (e.type == EdgeType.flat || this.type == EdgeType.flat) { + return false; + } else if (e.type == EdgeType.inner) { + return this.type == EdgeType.outer; + } else if (e.type == EdgeType.outer) { + return this.type == EdgeType.inner; + } else { + return false; + } + } + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/EdgeType.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/EdgeType.java new file mode 100644 index 0000000..944d896 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/EdgeType.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_6_Jigsaw; + +enum EdgeType { + + inner, outer, flat +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Piece.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Piece.java new file mode 100644 index 0000000..7a56c9c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Piece.java @@ -0,0 +1,28 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_6_Jigsaw; + +public class Piece { + + Edge[] edges; + + public PieceType getPieceType() { + int flat_count = 0; + for (int i = 0; i < 4; i++) { + if (edges[i].type == EdgeType.flat) { + ++flat_count; + } + } + if (flat_count == 2) { + return PieceType.corner; + } else if (flat_count == 1) { + return PieceType.border; + } else { + return PieceType.inner; + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/PieceType.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/PieceType.java new file mode 100644 index 0000000..402db8d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/PieceType.java @@ -0,0 +1,8 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_6_Jigsaw; + +enum PieceType{ + corner, border, inner +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Puzzle.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Puzzle.java new file mode 100644 index 0000000..d8ad2ce --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_6_Jigsaw/Puzzle.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_6_Jigsaw; +public class Puzzle { + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Conversation.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Conversation.java new file mode 100644 index 0000000..c8f1ab4 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Conversation.java @@ -0,0 +1,23 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +import java.math.BigInteger; +import java.util.ArrayList; + +public abstract class Conversation { + + ArrayList messages; + ArrayList participants; + BigInteger id; + + public Conversation(BigInteger _id) { + this.id = _id; + messages = new ArrayList<>(); + participants = new ArrayList<>(); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/GroupChat.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/GroupChat.java new file mode 100644 index 0000000..cc13906 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/GroupChat.java @@ -0,0 +1,21 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +import java.math.BigInteger; + +public class GroupChat extends Conversation { + + public GroupChat(BigInteger _id, User _creater) { + super(_id); + participants.add(_creater); + } + + public void addParticipant(User _participant) { + participants.add(_participant); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Message.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Message.java new file mode 100644 index 0000000..d49224a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Message.java @@ -0,0 +1,22 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +import java.util.Date; + +public class Message { + + public String message; + public Date send_time; + public User sender; + + public Message(String _msg, Date _sendtime, User _poster) { + this.message = _msg; + this.send_time = _sendtime; + this.sender = _poster; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/PrivateChat.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/PrivateChat.java new file mode 100644 index 0000000..ccd0ec4 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/PrivateChat.java @@ -0,0 +1,18 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +import java.math.BigInteger; + +public class PrivateChat extends Conversation { + + public PrivateChat(BigInteger _id, User _from, User _to) { + super(_id); + participants.add(_from); + participants.add(_to); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Request.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Request.java new file mode 100644 index 0000000..3eb52ea --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/Request.java @@ -0,0 +1,21 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +public class Request { + + public User from; + public User to; + public RequestStatusType status; + + public Request(User _from, User _to) { + this.from = _from; + this.to = _to; + status = RequestStatusType.Unread; + } + + public static void main(String[] args) { + } + +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/RequestStatusType.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/RequestStatusType.java new file mode 100644 index 0000000..e1b7cea --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/RequestStatusType.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +public enum RequestStatusType { + + Approved, Declined, Read, Unread +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/User.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/User.java new file mode 100644 index 0000000..a0af9fc --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/User.java @@ -0,0 +1,81 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; + +public class User { + + private UserStatus status; + private BigInteger id; + private String nickname; + private String account; + public ArrayList contacts; + public ArrayList send_list; + public ArrayList receive_list; + public ArrayList groupchats; + public ArrayList privatechats; + + public User(BigInteger _id, String _nickname, String _account) { + this.id = _id; + this.nickname = _nickname; + this.account = _account; + status = new UserStatus(); + contacts = new ArrayList<>(); + send_list = new ArrayList<>(); + receive_list = new ArrayList<>(); + groupchats = new ArrayList<>(); + privatechats = new ArrayList<>(); + } + + public BigInteger getId() { + return id; + } + + public void Speak(String msg, Conversation s) { + Date now = new Date(); + Message m = new Message(msg, now, this); + if (s instanceof PrivateChat) { + if (s.participants.contains(this) && privatechats.contains(s)) { + s.messages.add(m); + } + } else if (s instanceof GroupChat) { + if (groupchats.contains(s)) { + s.messages.add(m); + } + } + } + + public void addConversation(Conversation c) { + if (c instanceof GroupChat) { + groupchats.add((GroupChat) c); + } else if (c instanceof PrivateChat) { + privatechats.add((PrivateChat) c); + } + } + + public void sendRequest(User _to) { + UserManager.getInstance().sendRequest(this, _to); + } + + public void approveRequest(User _to) { + UserManager.getInstance().approveRequest(this, _to); + } + + public void declineRequest(User _to) { + UserManager.getInstance().declineRequest(this, _to); + } + + public static void main(String[] args) { + User u = new User(BigInteger.ONE, "Sanqiang", "zsq@131x.com"); + Conversation c = new GroupChat(BigInteger.ONE, u); + u.addConversation(c); + if (u.groupchats.contains(c)) { + System.out.println("Ok"); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserManager.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserManager.java new file mode 100644 index 0000000..66d783d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserManager.java @@ -0,0 +1,60 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +import CareerCup.ObjectOrientedDesign.Q8_10_HashTable.HashTable; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Random; + +public class UserManager { + + private static UserManager instance = null; + + private UserManager() { + db = new HashTable<>(); + } + + public static UserManager getInstance() { + if (instance == null) { + instance = new UserManager(); + } + return instance; + } + HashTable db; + + public void register(String _nickname, String _account) { + BigInteger id = BigInteger.probablePrime(10, new Random()); + User ur = new User(id, _nickname, _account); + db.put(id, ur); + } + + public void sendRequest(User _from, User _to) { + Request r = new Request(_from, _to); + _to.receive_list.add(r); + } + + public void approveRequest(User _from, User _to) { + ArrayList list = _to.receive_list; + for (Request request : list) { + if (request.from == _from) { + request.status = RequestStatusType.Approved; + } + } + _to.contacts.add(_from.getId()); + _from.contacts.add(_to.getId()); + } + + public void declineRequest(User _from, User _to) { + ArrayList list = _to.receive_list; + for (Request request : list) { + if (request.from == _from) { + request.status = RequestStatusType.Declined; + } + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserStatus.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserStatus.java new file mode 100644 index 0000000..2f3816b --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserStatus.java @@ -0,0 +1,13 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +public class UserStatus { + + public String message; + public UserStatusType status; + + public UserStatus() { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserStatusType.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserStatusType.java new file mode 100644 index 0000000..b40e045 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_ChatServer/UserStatusType.java @@ -0,0 +1,10 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 24, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_ChatServer; + +enum UserStatusType { + + Online, Offline, Busy, Away, Inavailable +} \ No newline at end of file diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Board.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Board.java new file mode 100644 index 0000000..fcf6d42 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Board.java @@ -0,0 +1,132 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_Othello; + +public class Board { + + private Piece[][] board; + private int height; + private int width; + int black_score = 0; + int white_score = 0; + + public Board(int _column, int _row) { + this.board = new Piece[_column][_row]; + height = _column; + width = _row; + initiailize(); + } + + private void initiailize() { + board[4][4] = new Piece(Color.Black); + board[5][5] = new Piece(Color.Black); + board[4][5] = new Piece(Color.White); + board[5][4] = new Piece(Color.White); + black_score = 2; + white_score = 2; + } + + public boolean placePiece(int col, int row, Color me) { + if (board[col][row] != null) { + return false; + } + int direction[] = new int[4]; + if (col >= 1 && board[col - 1][row] != null && board[col - 1][row].getColor() != me) { + direction[0] = placePieceHelper(col - 1, row, me, Direciton.Up); + if (direction[0] > 0) { + //board[col - 1][row].flip(); + } + + } + if (col < height - 2 && board[col + 1][row] != null && board[col + 1][row].getColor() != me) { + direction[1] = placePieceHelper(col + 1, row, me, Direciton.Down); + if (direction[1] > 0) { + //board[col + 1][row].flip(); + } + } + if (row >= 1 && board[col][row - 1] != null && board[col][row - 1].getColor() != me) { + direction[2] = placePieceHelper(col, row - 1, me, Direciton.Left); + if (direction[2] > 0) { + //board[col][row - 1].flip(); + } + } + if (row < width - 2 && board[col][row + 1] != null && board[col][row + 1].getColor() != me) { + direction[3] = placePieceHelper(col, row + 1, me, Direciton.Right); + if (direction[3] > 0) { + //board[col][row + 1].flip(); + } + } + int count = 0; + for (int i : direction) { + count += i; + } + if (count <= 0) { + return false; + } else { + board[col][row] = new Piece(me); + updateScore(me, count); + return true; + } + } + + private int placePieceHelper(int col, int row, Color me, Direciton d) { + int h = 0, v = 0; + switch (d) { + case Up: + v = -1; + break; + case Down: + v = 1; + break; + case Left: + h = -1; + break; + case Right: + h = 1; + break; + } + if (board[col][row] == null || board[col][row].getColor() == me) { + return 0; + } + if (col < 0 || row < 0 || col > height - 1 || row > width - 1) { + return -1; + } + int count = placePieceHelper(col + v, row + h, me, d); + if (count >= 0) { + board[col][row].flip(); + return 1 + count; + } else { + return -1; + } + } + + private void updateScore(Color color, int num) { + if (color == Color.Black) { + black_score += num + 1; + white_score -= num; + } else { + black_score -= num; + white_score += num + 1; + } + } + + public void print() { + for (int col = 0; col < height; col++) { + for (int row = 0; row < width; row++) { + if (board[col][row] == null) { + System.out.print("_"); + } else if (board[col][row].getColor() == Color.Black) { + System.out.print("B"); + } else if (board[col][row].getColor() == Color.White) { + System.out.print("W"); + } + System.out.print(" "); + } + System.out.println(); + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Color.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Color.java new file mode 100644 index 0000000..596910c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Color.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_Othello; + +enum Color { + + Black, White +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Direciton.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Direciton.java new file mode 100644 index 0000000..cdc00e7 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Direciton.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_Othello; + +enum Direciton { + + Up, Down, Left, Right +} \ No newline at end of file diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Game.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Game.java new file mode 100644 index 0000000..743cbb2 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Game.java @@ -0,0 +1,40 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_Othello; + +public class Game { + + private int column = 10; + private int row = 10; + private Board board; + private static Game instance = null; + private Player players[]; + + private Game() { + board = new Board(column, row); + players = new Player[2]; + players[0] = new Player(Color.Black); + players[1] = new Player(Color.White); + } + + public static Game getInstance() { + if (instance == null) { + instance = new Game(); + } + return instance; + } + + public Board getBoard() { + return board; + } + + public static void main(String[] args) { + Game g = Game.getInstance(); + Board b = g.getBoard(); + b.print(); + boolean result = b.placePiece(4, 3, Color.White); + b.placePiece(5, 6, Color.White); + b.print(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Piece.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Piece.java new file mode 100644 index 0000000..8e6db3c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Piece.java @@ -0,0 +1,32 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_Othello; + +public class Piece { + + private Color color; + + public void setColor(Color _color) { + this.color = _color; + } + + public Color getColor() { + return color; + } + + public Piece(Color _color) { + this.color = _color; + } + + public void flip() { + if (this.getColor() == Color.Black) { + this.setColor(Color.White); + } else { + this.setColor(Color.Black); + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Player.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Player.java new file mode 100644 index 0000000..70cc8d1 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_8_Othello/Player.java @@ -0,0 +1,16 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_8_Othello; + +public class Player { + + public Color flag; + + public Player(Color _color) { + this.flag = _color; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/Directory.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/Directory.java new file mode 100644 index 0000000..fe4c66d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/Directory.java @@ -0,0 +1,56 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 19, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_9_FileSystem; + +import java.util.HashSet; + +public class Directory extends Entry { + + public HashSet files; + + public Directory(String _name, Directory _parent) { + super(_name, _parent); + files = new HashSet<>(); + } + + @Override + public int size() { + int size = 0; + for (Entry e : files) { + size += e.size(); + } + return size; + } + + @Override + public void delete() { + for (Entry e : files) { + e.delete(); + } + this.remove = true; + } + + public void deleteEntry(Entry e) { + files.remove(e); + } + + public void addEntry(Entry e) { + files.add(e); + } + + public int numfiles() { + int count = 0; + for (Entry e : files) { + if (e instanceof File) { + ++count; + } else if (e instanceof Directory) { + count += ((Directory) e).numfiles(); + } + } + return count; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/Entry.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/Entry.java new file mode 100644 index 0000000..e816c1a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/Entry.java @@ -0,0 +1,36 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 19, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_9_FileSystem; + +public abstract class Entry { + + public long date_create; + public long date_update; + public long date_access; + public String name; + public Directory parent; + public boolean remove; + + public Entry(String _name, Directory _parent) { + this.name = _name; + this.parent = _parent; + date_create = System.currentTimeMillis(); + date_update = System.currentTimeMillis(); + date_access = System.currentTimeMillis(); + remove = false; + } + + public void deleteParent() { + if (parent != null) { + parent.delete(); + } + } + + public abstract int size(); + + public abstract void delete(); + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/File.java b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/File.java new file mode 100644 index 0000000..56b6a60 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ObjectOrientedDesign/Q8_9_FileSystem/File.java @@ -0,0 +1,30 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 19, 2012 + */ +package CareerCup.ObjectOrientedDesign.Q8_9_FileSystem; + +public class File extends Entry { + + public String content; + public int size; + + public File(String _name, Directory _parent, String _content) { + super(_name, _parent); + this.content = _content; + this.size = _content.length(); + } + + @Override + public int size() { + return size; + } + + @Override + public void delete() { + parent.files.remove(this); + this.remove = true; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_10_CreateStackBox.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_10_CreateStackBox.java new file mode 100644 index 0000000..3e8792e --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_10_CreateStackBox.java @@ -0,0 +1,70 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.ArrayList; +import java.util.HashMap; + +public class Q9_10_CreateStackBox { + + class Box { + + public int width; + public int height; + public int depth; + + public boolean canBeAbove(Box another) { + if (another == null) { + return true; + } else { + return this.width < another.width && this.height < another.height && this.depth < another.depth; + } + } + + public void print() { + System.out.append("W:" + width + " H:" + height + " D:" + depth); + } + } + + private int getHeight(ArrayList list) { + if (list == null) { + return 0; + } + int height = 0; + for (Box box : list) { + height += box.height; + } + return height; + } + HashMap> cache = new HashMap<>(); + + public ArrayList getLongest(Box[] boxes, Box bottom) { + if (bottom != null && cache.containsKey(bottom)) { + return cache.get(bottom); + } + ArrayList solution = null; + int maxheight = 0; + for (Box box : boxes) { + if (box.canBeAbove(bottom)) { + ArrayList temp_solution = getLongest(boxes, box); + int temp_height = getHeight(temp_solution); + if (temp_height > maxheight) { + maxheight = temp_height; + solution = temp_solution; + } + } + } + if (bottom != null) { + solution.add(0, bottom); + } + if (solution == null) { + solution = new ArrayList<>(); + } + cache.put(bottom, solution); + return solution; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_11_BinaryRepresentation.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_11_BinaryRepresentation.java new file mode 100644 index 0000000..9cb043a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_11_BinaryRepresentation.java @@ -0,0 +1,67 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.HashMap; +import sun.security.krb5.internal.KDCOptions; + +public class Q9_11_BinaryRepresentation { + + HashMap cache = new HashMap<>(); + + public int f(String text, int s, int e, boolean result) { + String key = String.valueOf(s) + (result ? "y" : "n") + String.valueOf(e); + if (cache.containsKey(key)) { + return cache.get(key); + } + if (s == e) { + if ((text.charAt(s) == '1' && result) || (text.charAt(s) == '0' && !result)) { + return 1; + } else { + return 0; + } + } + int ways = 0; + if (result) { + for (int m = s + 1; m <= e; m += 2) { + switch (text.charAt(m)) { + case '&': + ways += f(text, s, m - 1, true) * f(text, m + 1, e, true); + break; + case '|': + ways += f(text, s, m - 1, true) * f(text, m + 1, e, false) + + f(text, s, m - 1, false) * f(text, m + 1, e, true) + + f(text, s, m - 1, true) * f(text, m + 1, e, true); + break; + case '^': + ways += f(text, s, m - 1, true) * f(text, m + 1, e, false) + + f(text, s, m - 1, false) * f(text, m + 1, e, true); + break; + } + } + } else { + for (int m = s + 1; m <= e; m += 2) { + switch (text.charAt(m)) { + case '&': + ways += f(text, s, m - 1, false) * f(text, m + 1, e, false) + + f(text, s, m - 1, false) * f(text, m + 1, e, true) + + f(text, s, m - 1, true) * f(text, m + 1, e, true); + break; + case '|': + ways += f(text, s, m - 1, false) * f(text, m + 1, e, false); + break; + case '^': + ways += f(text, s, m - 1, true) * f(text, m + 1, e, true) + + f(text, s, m - 1, false) * f(text, m + 1, e, false); + break; + } + } + } + cache.put(key, ways); + return ways; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_1_CountWays.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_1_CountWays.java new file mode 100644 index 0000000..d330ca0 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_1_CountWays.java @@ -0,0 +1,32 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.HashMap; + +public class Q9_1_CountWays { + + private HashMap cache = new HashMap<>(); + + public int count(int n) { + if (n == 0) { + return 1; + } else if (n < 0) { + return 0; + } + if (cache.containsKey(n)) { + return cache.get(n); + } + int ways = count(n - 1) + count(n - 2) + count(n - 3); + cache.put(n, ways); + return ways; + } + + public static void main(String[] args) { + Q9_1_CountWays q91 = new Q9_1_CountWays(); + int ways = q91.count(3); + System.out.println(ways); + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_2_GetRobotPath.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_2_GetRobotPath.java new file mode 100644 index 0000000..870d8e9 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_2_GetRobotPath.java @@ -0,0 +1,62 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.ArrayList; +import java.util.HashMap; + +public class Q9_2_GetRobotPath { + + private HashMap cache = new HashMap<>(); + public boolean isConnected(int x, int y, ArrayList path) { + boolean result = false; + Point p = new Point(x, y); + path.add(p); + if (cache.containsKey(p)) { + return cache.get(p); + } + if (x == 0 && y == 0) { + return true; + } + if (x > 0 && isfree(x - 1, y)) { + result = isConnected(x - 1, y, path); + } + if (result) { + return true; + } + if (y > 0 && isfree(x, y - 1)) { + result = isConnected(x, y - 1, path); + } + if (!result) { + path.remove(p); + } + cache.put(p, result); + return result; + } + + boolean isfree(int x, int y) { + return true; + } + + class Point { + + int x; + int y; + + public Point(int _x, int _y) { + this.x = _x; + this.y = _y; + } + } + + public static void main(String[] args) { + Q9_2_GetRobotPath q92 = new Q9_2_GetRobotPath(); + ArrayList path = new ArrayList<>(); + boolean result = q92.isConnected(41, 51, path); + System.out.println(result); + for (Point point : path) { + System.out.println(point.x + "," + point.y); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_3_MagicIndex.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_3_MagicIndex.java new file mode 100644 index 0000000..b16993d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_3_MagicIndex.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +public class Q9_3_MagicIndex { + + public int find(int[] array) { + int s = 0, length = array.length, e = length - 1; + while (s <= e) { + int m = s + (e - s) / 2; + if (m == array[m]) { + return m; + } else if (m > array[m]) { + s = m + 1; + } else { + e = m - 1; + } + } + return -1; + } + + public int findWithOverlap(int[] array, int s, int e) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + if (m == array[m]) { + return m; + } + int l = Math.min(array[m], m - 1); + int result = findWithOverlap(array, s, l); + if (result != -1) { + return result; + } + int h = Math.max(array[m], m + 1); + result = findWithOverlap(array, h, e); + return result; + } + + public static void main(String[] args) { + Q9_3_MagicIndex q93 = new Q9_3_MagicIndex(); + int[] arr1 = {-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13}; + int i1 = q93.find(arr1); + System.out.println(i1); + int[] arr2 = {-10, -5, 2, 2, 2, 3, 4, 8, 9, 12, 13}; + int i2 = q93.findWithOverlap(arr2, 0, arr2.length - 1); + System.out.println(i2); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_4_Subsets.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_4_Subsets.java new file mode 100644 index 0000000..115e685 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_4_Subsets.java @@ -0,0 +1,73 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.ArrayList; + +public class Q9_4_Subsets { + + public ArrayList> getSubsets2(ArrayList set) { + ArrayList> solution = new ArrayList<>(); + int length = set.size(), subset_size = 1 << length; + for (int i = 0; i < subset_size; i++) { + ArrayList temp = new ArrayList<>(); + for (int pos = 0; pos < length; pos++) { + if (((1 << pos) & i) > 0) { + temp.add(set.get(pos)); + } + } + solution.add(temp); + } + return solution; + } + + public ArrayList> getSubsets(ArrayList set, int index) { + if (index == set.size()) { + ArrayList> solution = new ArrayList<>(); + ArrayList empty = new ArrayList<>(); + solution.add(empty); + return solution; + } + ArrayList> solution = getSubsets(set, index + 1); + char ch = set.get(index); + ArrayList> temp = new ArrayList<>(); + for (ArrayList arrayList : solution) { + ArrayList temp_item = new ArrayList<>(); + temp_item.addAll(arrayList); + temp_item.add(ch); + temp.add(temp_item); + } + solution.addAll(temp); + return solution; + } + + public static void main(String[] args) { + ArrayList set = new ArrayList<>(); + String text = Util.TestUtil.generateArrayString(20, 9); + for (Character ch : text.toCharArray()) { + set.add(ch); + } + Q9_4_Subsets q94 = new Q9_4_Subsets(); + long t1 = System.currentTimeMillis(); + ArrayList> solution1 = q94.getSubsets(set, 0); + //print(solution1); + long t2 = System.currentTimeMillis(); + ArrayList> solution2 = q94.getSubsets2(set); + //print(solution2); + long t3 = System.currentTimeMillis(); + long sp1 = t2 - t1, sp2 = t3 - t2; + System.out.println(solution1.size() + " Cost " + sp1); + System.out.println(solution2.size() + " Cost " + sp2); + } + + static void print(ArrayList> solution) { + for (ArrayList arrayList : solution) { + for (Character character : arrayList) { + System.out.print(character); + } + System.out.println(); + } + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_5_Permutation.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_5_Permutation.java new file mode 100644 index 0000000..13b0c9b --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_5_Permutation.java @@ -0,0 +1,45 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.ArrayList; + +public class Q9_5_Permutation { + + public ArrayList getPermuatation(String text) { + if (text.length() == 1) { + ArrayList solution = new ArrayList<>(); + solution.add(text); + return solution; + } + String current = text.substring(0, 1); + String remaining = text.substring(1); + ArrayList solution = getPermuatation(remaining); + ArrayList next_solution = new ArrayList<>(); + for (int i = 0; i < solution.size(); i++) { + ArrayList temp = inject(solution.get(i), current); + next_solution.addAll(temp); + } + return next_solution; + } + + private ArrayList inject(String text, String ch) { + ArrayList solution = new ArrayList<>(); + for (int i = 0; i <= text.length(); i++) { + String left = text.substring(0, i); + String right = text.substring(i); + solution.add(left + ch + right); + } + return solution; + } + + public static void main(String[] args) { + String text = "abc"; + Q9_5_Permutation q95 = new Q9_5_Permutation(); + ArrayList solution = q95.getPermuatation(text); + for (String string : solution) { + System.out.println(string); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_6_ValidParentheses.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_6_ValidParentheses.java new file mode 100644 index 0000000..293ad13 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_6_ValidParentheses.java @@ -0,0 +1,39 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +public class Q9_6_ValidParentheses { + + public void printParenthesis(int pair) { + boolean[] presentation = new boolean[pair * 2]; + printParentheses(pair, pair, presentation, 0); + } + + private void printParentheses(int left, int right, boolean[] presentation, int index) { + if (left == 0 && right == 0) { + for (int i = 0; i < presentation.length; i++) { + if (presentation[i]) { + System.out.print("("); + } else { + System.out.print(")"); + } + } + System.out.println(); + } + if (left > 0) { + presentation[index] = true; + printParentheses(left - 1, right, presentation, index + 1); + } + + if (left < right) { + presentation[index] = false; + printParentheses(left, right - 1, presentation, index + 1); + } + } + + public static void main(String[] args) { + Q9_6_ValidParentheses q96 = new Q9_6_ValidParentheses(); + q96.printParenthesis(3); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_7_PaintFill.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_7_PaintFill.java new file mode 100644 index 0000000..cdc180e --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_7_PaintFill.java @@ -0,0 +1,27 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +public class Q9_7_PaintFill { + + enum Color { + + Red, Green, Yellow + } + + public void paint(Color[][] canvas, int col, int row, Color ncolor, Color ocolor) { + int height = canvas.length, width = canvas[0].length; + if (col < 0 || col >= height || row < 0 || row >= width || canvas[col][row] != ocolor) { + return; + } + canvas[col][row] = ncolor; + paint(canvas, col - 1, row, ncolor, ocolor); + paint(canvas, col + 1, row, ncolor, ocolor); + paint(canvas, col, row - 1, ncolor, ocolor); + paint(canvas, col, row + 1, ncolor, ocolor); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_8_CountCoin.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_8_CountCoin.java new file mode 100644 index 0000000..b599421 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_8_CountCoin.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +import java.util.HashMap; + +public class Q9_8_CountCoin { + + HashMap cache = new HashMap<>(); + + public int count(int charge, int coin) { + if (cache.containsKey(charge)) { + //System.out.println(charge + ":" + cache.get(charge)); + //return cache.get(charge); + } + int ways = 0; + int next_coin = 0; + switch (coin) { + case 25: + next_coin = 10; + break; + case 10: + next_coin = 5; + break; + case 5: + next_coin = 1; + break; + case 1: + return 1; + default: + return 0; + } + for (int i = 0; charge - i * coin >= 0; i++) { + ways += count(charge - i * coin, next_coin); + } + //cache.put(charge, ways); + return ways; + } + + public static void main(String[] args) { + Q9_8_CountCoin q98 = new Q9_8_CountCoin(); + int ways = q98.count(50, 25); + System.out.println(ways); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_9_PlaceQueen.java b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_9_PlaceQueen.java new file mode 100644 index 0000000..e2eddc5 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/RecursiveAndDP/Q9_9_PlaceQueen.java @@ -0,0 +1,59 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.RecursiveAndDP; + +public class Q9_9_PlaceQueen { + + final int GRID_SIZE = 8; + + public void place() { + place(0, new int[GRID_SIZE]); + } + + public void place(int row, int[] chess) { + if (row == GRID_SIZE) { + print(chess); + return; + } + + for (int i = 0; i < GRID_SIZE; i++) { + chess[row] = i; + if (checkValid(row, chess)) { + place(row + 1, chess); + } + } + } + + private boolean checkValid(int row, int[] chess) { + for (int i = 0; i < row; i++) { + int w = Math.abs(chess[i] - chess[row]); + int h = Math.abs(i - row); + if (w == 0 || w == h) { + return false; + } + } + return true; + } + + private void print(int[] chess) { + for (int i = 0; i < GRID_SIZE; i++) { + int col = chess[i]; + int j = 0; + for (; j < col; j++) { + System.out.print("_"); + } + System.out.print("*"); + for (j = col + 1; j < GRID_SIZE; j++) { + System.out.print("_"); + } + System.out.println(); + } + System.out.println(); + } + + public static void main(String[] args) { + Q9_9_PlaceQueen q99 = new Q9_9_PlaceQueen(); + q99.place(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ScalabilityAndMemoryLimits/Q10_3_4_BitSet/BitSet.java b/Algorithm-Java-Backup/src/CareerCup/ScalabilityAndMemoryLimits/Q10_3_4_BitSet/BitSet.java new file mode 100644 index 0000000..569af44 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ScalabilityAndMemoryLimits/Q10_3_4_BitSet/BitSet.java @@ -0,0 +1,43 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 28, 2012 + */ +package CareerCup.ScalabilityAndMemoryLimits.Q10_3_4_BitSet; + +public class BitSet { + + long[] buffer; + + public BitSet(int _size) { + if (_size >> 10 == 0) { + this.buffer = new long[1]; + } else { + this.buffer = new long[_size >> 10]; + } + } + + public BitSet(int _size, boolean buffer_size) { + if (buffer_size) { + this.buffer = new long[_size]; + } else { + // + } + } + + public void set(int n) { + int word_num = n >> 10; //divid by 32 + int bit_num = n & 0x3FF; //mod 32 + buffer[word_num] |= 1 << bit_num; + } + + public boolean get(int n) { + int word_num = n >> 10; + int bit_num = n & 0x3FF; + return (buffer[word_num] & 1 << bit_num) != 0; + } + + public static void main(String[] args) { + BitSet bs = new BitSet(5); + bs.set(3); + System.out.println(bs.get(0)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/HeapSort.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/HeapSort.java new file mode 100644 index 0000000..ce3dcfe --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/HeapSort.java @@ -0,0 +1,56 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; + +public class HeapSort> extends SortBase { + + public HeapSort(T[] _array) { + super(_array); + } + + public int getLeft(int index) { + return index * 2 + 1; + } + + public int getRight(int index) { + return index * 2 + 2; + } + + public void maxHeapify(int index, int size) { + int l = getLeft(index); + int r = getRight(index); + int MaxIndex = index; + if (l < size && array[l].compareTo(array[MaxIndex]) > 0) { + MaxIndex = l; + } + if (r < size && array[r].compareTo(array[MaxIndex]) > 0) { + MaxIndex = r; + } + if (MaxIndex != index) { + swap(MaxIndex, index); + maxHeapify(MaxIndex, size); + } + } + + @Override + void sort() { + int i, length = array.length; + for (i = length / 2 - 1; i >= 0; --i) { + maxHeapify(i, length); + } + for (i = length - 1; i >= 0; --i) { + swap(i, 0); + maxHeapify(0, i); + } + } + + public static void main(String[] args) { + Integer[] arr = {8, 6, 4, 2, 3}; + HeapSort hs = new HeapSort<>(arr); + hs.sort(); + for (Integer integer : hs.array) { + System.out.println(integer); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/InsertSort.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/InsertSort.java new file mode 100644 index 0000000..a6bda21 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/InsertSort.java @@ -0,0 +1,44 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; + +public class InsertSort> extends SortBase { + + public InsertSort(T[] _array) { + super(_array); + } + + @Override + void sort() { + int i, j, length = array.length; + for (i = 0; i < length; ++i) { + for (j = i; j - 1 >= 0 && array[j].compareTo(array[j - 1]) < 0; --j) { + swap(j, j - 1); + } + } + } + final int[] Marcin_Ciura_Gap = {701, 301, 132, 57, 23, 10, 4, 1}; + + void sort_shell() { + int i, j, length = array.length; + for (int step : Marcin_Ciura_Gap) { + for (i = 0; i < length; i += step) { + for (j = i; j - step >= 0 && array[j].compareTo(array[j - step]) < 0; j -= step) { + swap(j, j - step); + } + } + } + + } + + public static void main(String[] args) { + Integer[] arr = {8, 6, 4, 2, 3, 0, 2, 10, 12}; + InsertSort is = new InsertSort<>(arr); + //is.sort(); + is.sort_shell(); + for (Integer integer : is.array) { + System.out.println(integer); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/MergeSort.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/MergeSort.java new file mode 100644 index 0000000..8b63791 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/MergeSort.java @@ -0,0 +1,74 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; + +public class MergeSort> extends SortBase { + + public MergeSort(T[] _array) { + super(_array); + } + + @Override + void sort() { + split(0, array.length - 1); + } + + void split(int s, int e) { + if (s >= e) { + return; + } + int m = s + (e - s) / 2; + split(s, m); + split(m + 1, e); + merge(s, e, m); + } + + //Java didnot support generic array creation + void merge(int s, int e, int m) { + Object[] ll = new Object[m - s + 1]; + Object[] rr = new Object[e - (m + 1) + 1]; + int i, j, k; + for (i = 0; i < ll.length; i++) { + ll[i] = array[s + i]; + } + for (i = 0; i < rr.length; i++) { + rr[i] = array[m + i + 1]; + } + i = 0; + j = 0; + k = s; + while (true) { + if (i == ll.length) { + while (j != rr.length) { + array[k++] = (T) rr[j++]; + } + break; + } + if (j == rr.length) { + while (i != ll.length) { + array[k++] = (T) ll[i++]; + } + break; + } + T l = (T) ll[i]; + T r = (T) rr[j]; + if (l.compareTo(r) <= 0) { + array[k++] = l; + i++; + } else { + array[k++] = r; + j++; + } + } + } + + public static void main(String[] args) { + Integer[] arr = {8, 6, 4, 2, 3}; + MergeSort ms = new MergeSort<>(arr); + ms.sort(); + for (Integer integer : ms.array) { + System.out.println(integer); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/NthBiggest.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/NthBiggest.java new file mode 100644 index 0000000..aca4998 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/NthBiggest.java @@ -0,0 +1,92 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; + +import java.util.Random; + +public class NthBiggest> extends SortBase { + + int k; + + public NthBiggest(T[] _array, int _k) { + super(_array); + this.k = _k; + } + + @Override + void sort() { + int i, length = array.length; + for (i = length / 2 - 1; i >= 0; --i) { + maxHeapify(i, length); + } + for (i = length - 1; i > length - 1 - k; --i) { + swap(0, i); + maxHeapify(0, i); + } + } + + void sort2() { + sort_selection(0, array.length - 1, k); + } + + void sort_selection(int s, int e, int k) { + int random = new Random().nextInt(e - s + 1) + s; + T pivot = array[random]; + int LeftEnd = selection_partition(s, e, pivot); + int LeftSize = LeftEnd - s + 1; + if (LeftSize == k) { + return; + } else if (LeftSize < k) { + sort_selection(LeftEnd + 1, e, k - LeftSize); + } else { + sort_selection(s, LeftEnd, k); + } + + } + + int selection_partition(int s, int e, T pivot) { + while (true) { + for (; s <= e && array[s].compareTo(pivot) <= 0; ++s); + for (; s <= e && array[e].compareTo(pivot) >= 0; --e); + if (s > e) { + return s - 1; + } + swap(s, e); + } + } + + private int getLeft(int index) { + return index * 2 + 1; + } + + private int getRight(int index) { + return index * 2 + 2; + } + + public void maxHeapify(int index, int size) { + int l = getLeft(index); + int r = getRight(index); + int MaxIndex = index; + if (l < size && array[l].compareTo(array[MaxIndex]) > 0) { + MaxIndex = l; + } + if (r < size && array[r].compareTo(array[MaxIndex]) > 0) { + MaxIndex = r; + } + if (MaxIndex != index) { + swap(index, MaxIndex); + maxHeapify(MaxIndex, size); + } + } + + public static void main(String[] args) { + Integer[] arr = {10,0, 9, 3, 8, 1,7, 6}; + NthBiggest nb = new NthBiggest<>(arr, 2); + //nb.sort(); + nb.sort2();; + for (Integer integer : nb.array) { + System.out.println(integer); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_1_Merge.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_1_Merge.java new file mode 100644 index 0000000..ba98e68 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_1_Merge.java @@ -0,0 +1,31 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.SortAndSearch; + +public class Q11_1_Merge { + + public void merge(int[] large, int[] small, int len_large, int len_small) { + int index_large = len_large - 1; + int index_small = len_small - 1; + int index = large.length - 1; + while (true) { + if (index_large < 0) { + while (index_small >= 0) { + large[index--] = small[index_small--]; + } + return; + } else if (index_small < 0) { + return; + } + if (large[index_large] <= small[index_small]) { + large[index--] = small[index_small--]; + } else { + large[index--] = large[index_large--]; + } + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_2_SortStrings.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_2_SortStrings.java new file mode 100644 index 0000000..a57af81 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_2_SortStrings.java @@ -0,0 +1,53 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.SortAndSearch; + +import java.util.Arrays; +import java.util.Comparator; + +public class Q11_2_SortStrings { + + public void sort(String[] list) { + Arrays.sort(list, new comp()); + } + + public class comp implements Comparator { + + @Override + public int compare(String t, String t1) { + if (isAnagram(t, t1)) { + return 0; + } else { + return t.hashCode() - t1.hashCode(); + } + } + + private boolean isAnagram(String t, String t1) { + int t_length = t.length(), t1_length = t1.length(), i; + if (t_length != t1_length) { + return false; + } + int[] tab = new int[0xff]; + for (i = 0; i < t_length; i++) { + ++tab[t.charAt(i)]; + } + for (i = 0; i < t1_length; i++) { + --tab[t1.charAt(i)]; + if (tab[t1.charAt(i)] < 0) { + return false; + } + } + return true; + } + } + + public static void main(String[] args) { + String[] list = {"op", "d", "abb", "po", "bab", "po", "ki"}; + Q11_2_SortStrings q112 = new Q11_2_SortStrings(); + q112.sort(list); + for (String string : list) { + System.out.println(string); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_3_SortRotatedArray.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_3_SortRotatedArray.java new file mode 100644 index 0000000..bf24f25 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_3_SortRotatedArray.java @@ -0,0 +1,44 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.SortAndSearch; + +public class Q11_3_SortRotatedArray { + + public int find(int[] arr, int s, int e, int target) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + if (arr[m] == target) { + return m; + } + if (arr[s] < arr[m]) { + if (target >= arr[s] && target <= arr[m]) { + return find(arr, s, m - 1, target); + } else { + return find(arr, m + 1, e, target); + } + } else if (arr[m] < arr[e]) { + if (target >= arr[m] && target <= arr[e]) { + return find(arr, m + 1, e, target); + } else { + return find(arr, s, m - 1, target); + } + } else { + if (arr[m] != arr[e]) { + return find(arr, m + 1, e, target); + } else { + int f = find(arr, m + 1, e, target); + if (f == -1) { + return find(arr, s, m + 1, target); + } else { + return f; + } + } + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_5_FindString.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_5_FindString.java new file mode 100644 index 0000000..0bfe67a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_5_FindString.java @@ -0,0 +1,35 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.SortAndSearch; + +public class Q11_5_FindString { + + public int find(String[] list, String target, int s, int e) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + if (list[m].length() == 0) { + int dif = 1; + while (m + dif <= e && m - dif >= s) { + if (list[m + dif].length() != 0) { + m = m + dif; + } else if (list[m - dif].length() != 0) { + m = m - dif; + } + ++dif; + } + } + if (target.compareTo(list[m]) > 0) { + return find(list, target, m + 1, e); + } else if (target.compareTo(list[m]) < 0) { + return find(list, target, s, m - 1); + } else { + return m; + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_6_FindMatrix.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_6_FindMatrix.java new file mode 100644 index 0000000..6306aae --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_6_FindMatrix.java @@ -0,0 +1,149 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.SortAndSearch; + +public class Q11_6_FindMatrix { + + public void find2(int[][] matrix, int target) { + int height = matrix.length, width = matrix[0].length; + int col = 0, row = width - 1; + while (row >= 0 && col < height) { + if (matrix[col][row] == target) { + System.out.println(col + "," + row); + return; + } else if (matrix[col][row] < target) { + ++col; + } else { + --row; + } + } + System.out.println("Not Find!!!"); + } + + public void find1(int[][] matrix, int target) { + int height = matrix.length, width = matrix[0].length; + Point e = new Point(height - 1, width - 1); + Point s = new Point(0, 0); + Point result = find1(matrix, target, s, e); + if (result == null) { + System.out.println("Not Find!!!"); + } else { + System.out.println(result.y + "," + result.x); + } + } + + public Point find1(int[][] matrix, int target, Point s, Point e) { + if (s.x > e.x || s.y > e.y) { + return null; + } + Point pivot = findPivot(matrix, target, s, e); + if (pivot.inBound(matrix) && matrix[pivot.y][pivot.x] == target) { + return pivot; + } + Point left_top = new Point(pivot.y, s.x); + Point left_bottom = new Point(e.y, pivot.x - 1); + Point right_top = new Point(s.y, pivot.x); + Point right_bottom = new Point(pivot.y - 1, e.x); + Point p = find1(matrix, target, left_top, left_bottom); + if (p == null) { + return find1(matrix, target, right_top, right_bottom); + } else { + return p; + } + } + + public Point findPivot(int[][] matrix, int target, Point s, Point e) { + if (s.x > e.x || s.y > e.y || !s.inBound(matrix) || !e.inBound(matrix)) { + return null; + } + Point ss = s.clone(); + int dif = Math.min(e.x - s.x, e.y - s.y); + Point ee = new Point(ss.y + dif, ss.x + dif); + Point m = null; + while (ss.lessThanEqualto(ee)) { + m = ss.getMedian(ee); + if (matrix[m.y][m.x] == target) { + return m; + } else if (matrix[m.y][m.x] < target) { + //ss.increment(); + ss.x = m.x + 1; + ss.y = m.y + 1; + } else { + ee.x = m.x - 1; + ee.y = m.y - 1; + //ee.decrement(); + } + } + return ss; + } + + class Point { + + public int x; + public int y; + + public Point() { + } + + public Point(int _y, int _x) { + this.x = _x; + this.y = _y; + } + + public void increment() { + ++this.x; + ++this.y; + } + + public void decrement() { + --this.x; + --this.y; + } + + public boolean lessThan(Point p) { + return this.x < p.x && this.y < p.y; + } + + public boolean moreThan(Point p) { + return this.x > p.x && this.y > p.y; + } + + public boolean lessThanEqualto(Point p) { + return this.x <= p.x && this.y <= p.y; + } + + public boolean moreThanEqualto(Point p) { + return this.x >= p.x && this.y >= p.y; + } + + public Point getMedian(Point p) { + return new Point((this.y + p.y) / 2, (this.x + p.x) / 2); + } + + public boolean inBound(int[][] matrix) { + int height = matrix.length, width = matrix[0].length; + if (this.x >= 0 && this.x < width && this.y >= 0 && this.y < height) { + return true; + } else { + return false; + } + } + + @Override + protected Point clone() { + return new Point(y, x); + } + } + + public static void main(String[] args) { + int[][] matrix = { + {15, 20, 70, 85}, + {20, 35, 80, 95}, + {30, 55, 95, 105}, + {40, 80, 120, 120} + }; + Q11_6_FindMatrix q116 = new Q11_6_FindMatrix(); + q116.find1(matrix, 20); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_7_LongestSubsequence.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_7_LongestSubsequence.java new file mode 100644 index 0000000..346206d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_7_LongestSubsequence.java @@ -0,0 +1,76 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.SortAndSearch; + +import java.util.ArrayList; + +public class Q11_7_LongestSubsequence { + + public ArrayList find(ArrayList items) { + int length = items.size(); + ArrayList[] solutions = new ArrayList[length]; + ArrayList best = null; + for (ArrayList list : solutions) { + best = setBest(list, best); + } + return best; + } + + public void findDP(ArrayList[] solutions, ArrayList items, int index) { + if (index == solutions.length) { + return; + } + HtWt cur = items.get(index); + ArrayList cur_best = null; + for (int i = 0; i < index; i++) { + ArrayList pre_best = solutions[i]; + cur_best = setBest(pre_best, cur_best); + } + ArrayList solution = new ArrayList<>(); + if (cur_best != null) { + solution.addAll(cur_best); + } + solution.add(cur); + solutions[index] = solution; + findDP(solutions, items, index + 1); + } + + private ArrayList setBest(ArrayList list1, ArrayList list2) { + if (list1 == null) { + return list2; + } else if (list2 == null) { + return list1; + } + if (list1.size() > list2.size()) { + return list1; + } else { + return list2; + } + } + + public static void main(String[] args) { + } + + class HtWt { + + public int height; + public int weight; + + public HtWt() { + } + + public HtWt(int h, int w) { + this.height = h; + this.weight = w; + } + + public boolean canBeAfter(HtWt hw) { + return this.height > hw.height && this.weight > hw.height; + } + + public boolean canBeBefore(HtWt hw) { + return this.height < hw.height && this.weight < hw.height; + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_8_RankNode.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_8_RankNode.java new file mode 100644 index 0000000..71fb3a8 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/Q11_8_RankNode.java @@ -0,0 +1,72 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 6, 2013 + */ +package CareerCup.SortAndSearch; + +import javax.xml.crypto.Data; + +public class Q11_8_RankNode { + + public class RankNode { + + public int data = 0; + public int order = 0; + public RankNode left = null; + public RankNode right = null; + + public RankNode(int _data, int _order) { + this.data = _data; + this.order = _order; + } + + public void insert(int _data) { + if (_data < this.data) { + if (left == null) { + left = new RankNode(_data, 0); + } else { + left.insert(_data); + } + ++this.order; + } else if (_data > this.data) { + if (right == null) { + right = new RankNode(_data, 0); + } else { + right.insert(_data); + } + } + } + + public int getOrder(int _data) { + if (_data == this.data) { + return this.order; + } + if (_data < this.data) { + if (left == null) { + return -1; + } else { + return left.getOrder(_data); + } + } else if (_data > this.data) { + if (right == null) { + return -1; + } else { + return 1 + this.order + right.getOrder(_data); + } + } + return -1; + } + + public int getOrder() { + int order = this.order; + RankNode node = this; + while (node.right != null) { + order += right.order; + node = node.right; + } + return order; + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/QuickSort.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/QuickSort.java new file mode 100644 index 0000000..2e757b3 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/QuickSort.java @@ -0,0 +1,83 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; + +import Util.TestUtil; +import java.util.Random; + +public class QuickSort> extends SortBase { + + public QuickSort(T[] _array) { + super(_array); + } + public boolean Random = false; + + @Override + void sort() { + split(0, array.length - 1); + } + + void split(int s, int e) { + if (s >= e) { + return; + } + int pivot = 0; + if (Random) { + pivot = partitionRandom(s, e); + } else { + pivot = partition(s, e); + } + split(s, pivot - 1); + split(pivot + 1, e); + } + + int partitionRandom(int s, int e) { + int pivot_ind = s + new Random().nextInt(e - s + 1); + T pivot_val = array[pivot_ind]; + swap(pivot_ind, s); + int a = s + 1, b = s + 1; + while (b <= e) { + if (array[b].compareTo(pivot_val) < 0) { + swap(b, a++); + } + ++b; + } + swap(a - 1, s); + return a - 1; + } + + int partition(int s, int e) { + T pivot = array[s]; + while (s < e) { + for (; s < e && array[e].compareTo(pivot) >= 0; --e); + array[s] = array[e]; + for (; s < e && array[s].compareTo(pivot) <= 0; ++s); + array[e] = array[s]; + } + array[s] = pivot; + return s; + } + + public static void main(String[] args) { + Integer[] arr = {8, 6, 4, 2, 3, 1, 2, 3, 4, 100, 9}; + QuickSort qs = new QuickSort<>(arr); + qs.Random = true; + qs.sort(); + for (Integer integer : qs.array) { + System.out.println(integer); + } + + Integer[] test1 = TestUtil.intToInteger(TestUtil.generateArray(0xffff)); + Integer[] test2 = test1.clone(); + long t1 = System.currentTimeMillis(); + QuickSort q1 = new QuickSort<>(test1); + q1.sort(); + long t2 = System.currentTimeMillis(); + QuickSort q2 = new QuickSort<>(test2); + q2.sort(); + long t3 = System.currentTimeMillis(); + long span1 = t2 - t1, span2 = t3 - t2; + System.out.print("Random:" + span1 + "\r\nFirst:" + span2); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/SelectSort.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/SelectSort.java new file mode 100644 index 0000000..6e7e7ef --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/SelectSort.java @@ -0,0 +1,36 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; + +public class SelectSort> extends SortBase { + + public SelectSort(T[] _array) { + super(_array); + } + + @Override + void sort() { + int k, i, j, length = array.length; + for (i = 0; i < length; i++) { + k = i; + for (j = i; j < length; j++) { + if (array[k].compareTo(array[j]) > 0) { + k = j; + } + } + if (k != i) { + swap(k, i); + } + } + } + + public static void main(String[] args) { + Integer[] arr = {8, 6, 4, 2, 3}; + SelectSort ss = new SelectSort<>(arr); + ss.sort(); + for (Integer integer : ss.array) { + System.out.println(integer); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/SortBase.java b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/SortBase.java new file mode 100644 index 0000000..5df85a1 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/SortAndSearch/SortBase.java @@ -0,0 +1,21 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package CareerCup.SortAndSearch; +public abstract class SortBase { + + public T[] array ; + public SortBase(T[] _array){ + this.array = _array; + } + + abstract void sort(); + + protected void swap(int a, int b) + { + T temp = array[a]; + array[a] = array[b]; + array[b] = temp; + } + +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_1_ThreeStacks.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_1_ThreeStacks.java new file mode 100644 index 0000000..595652d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_1_ThreeStacks.java @@ -0,0 +1,166 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 3, 2013 + */ +package CareerCup.StacksAndQueues; + +public class Q3_1_ThreeStacks { + + final int NUM_BUFFER = 5; + final int NUM_STACK = 3; + + public class Stack { + + int[] buffer = new int[NUM_BUFFER]; + StackData[] stack_data = new StackData[NUM_STACK]; + + public Stack() { + for (int i = 0; i < NUM_STACK; i++) { + stack_data[i] = new StackData(NUM_BUFFER / NUM_STACK * i, NUM_BUFFER / 3); + } + } + + public int getTotalCapacity() { + int capacity = 0; + for (int i = 0; i < NUM_STACK; i++) { + capacity += stack_data[i]._capacity; + } + return capacity; + } + + public boolean push(int val, int target) { + StackData sd = stack_data[target]; + if (sd._pointer == sd._size - 1) { + expand(target); + } else if (getTotalCapacity() == NUM_BUFFER) { + System.out.println("Overflow"); + return false; + } + buffer[next(sd._pointer)] = val; + sd._pointer = next(sd._pointer); + ++sd._size; + return true; + } + + void expand(int target) { + StackData sd = stack_data[target]; + shift((target + 1) % NUM_STACK); + ++sd._capacity; + } + + void shift(int target) { + StackData sd = stack_data[target]; + if (sd._capacity == sd._size) { + shift((target + 1) % NUM_STACK); + for (int i = (sd._start + sd._capacity - 1) % NUM_BUFFER; sd.isInStackData(i, NUM_BUFFER); i = last(i)) { + buffer[i] = buffer[last(i)]; + } + sd._start = next(sd._start); + sd._pointer = next(sd._pointer); + } else { + for (int i = (sd._start + sd._capacity - 1) % NUM_BUFFER; sd.isInStackData(i, NUM_BUFFER); i = last(i)) { + buffer[i] = buffer[last(i)]; + } + sd._start = next(sd._start); + sd._pointer = next(sd._pointer); + --sd._capacity; + } + } + + public int pop(int target) { + StackData sd = stack_data[target]; + if (sd._pointer < 0) { + System.out.println("No Data"); + return Integer.MIN_VALUE; + } + int val = buffer[sd._pointer]; + buffer[sd._pointer] = -1; + --sd._capacity; + sd._pointer = last(sd._pointer); + return val; + } + + public int peek(int target) { + StackData sd = stack_data[target]; + if (sd._pointer < 0) { + System.out.println("No Data"); + return Integer.MIN_VALUE; + } + int val = buffer[sd._pointer]; + return val; + } + + int next(int i) { + if (i == NUM_BUFFER - 1) { + return 0; + } else { + return i + 1; + } + } + + int last(int i) { + if (i == 0) { + return NUM_BUFFER - 1; + } else { + return i - 1; + } + } + + void print() { + for (int i = 0; i < NUM_STACK; i++) { + StackData sd = stack_data[i]; + System.out.print("T: " + i + " "); + for (int j = 0; j < sd._capacity; j++) { + System.out.print(buffer[sd._pointer + j]); + } + System.out.println(); + } + } + + void printbuffer() { + for (int i = 0; i < NUM_BUFFER; i++) { + System.out.print(buffer[i]); + } + } + } + + class StackData { + + int _pointer; + int _start; + int _capacity; //volumn + int _size; //used + + public StackData(int start, int size) { + this._start = start; + this._size = size; + this._pointer = start - 1; + this._capacity = 0; + } + + public boolean isInStackData(int i, int total) { + if (_start + _capacity < total) { + return i >= _start && i < _start + _capacity; + } else { + return (i >= _start && i < total) || (i < _start && i < (_size + _capacity) && i >= 0); + } + } + } + + public static void main(String[] args) { + Q3_1_ThreeStacks q31 = new Q3_1_ThreeStacks(); + Q3_1_ThreeStacks.Stack stack = q31.new Stack(); + stack.push(9, 0); + stack.push(8, 0); + stack.push(7, 0); + stack.push(6, 0); + stack.push(5, 0); + System.out.println(stack.pop(0)); + System.out.println(stack.pop(0)); + System.out.println(stack.pop(0)); + System.out.println(stack.pop(0)); + stack.push(11, 1); + stack.push(22, 2); + System.out.println(stack.pop(2)); + System.out.println(stack.pop(1)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_2_MinStack.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_2_MinStack.java new file mode 100644 index 0000000..072b64c --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_2_MinStack.java @@ -0,0 +1,55 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 3, 2013 + */ +package CareerCup.StacksAndQueues; + +import java.util.Stack; + +public class Q3_2_MinStack { + + class MinStack extends Stack { + + Stack Helper; + + public MinStack() { + super(); + Helper = new Stack<>(); + } + + @Override + public Integer push(Integer e) { + if (Helper.isEmpty() || e < Helper.peek()) { + Helper.push(e); + } + return super.push(e); + } + + @Override + public synchronized Integer pop() { + if (Helper.peek() == super.peek()) { + Helper.pop(); + } + return super.pop(); + } + + public Integer min() { + if (Helper.isEmpty()) { + return Integer.MAX_VALUE; + } + return Helper.peek(); + } + } + + public static void main(String[] args) { + Q3_2_MinStack q32 = new Q3_2_MinStack(); + Q3_2_MinStack.MinStack ms = q32.new MinStack(); + ms.push(2); + ms.push(3); + ms.push(1); + ms.push(4); + System.out.println(ms.pop() + " Min:" + ms.min()); + System.out.println(ms.pop() + " Min:" + ms.min()); + System.out.println(ms.pop() + " Min:" + ms.min()); + System.out.println(ms.peek() + " Min:" + ms.min()); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_3_SetOfStacks.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_3_SetOfStacks.java new file mode 100644 index 0000000..89d1358 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_3_SetOfStacks.java @@ -0,0 +1,105 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 3, 2013 + */ +package CareerCup.StacksAndQueues; + +import java.util.ArrayList; +import java.util.Stack; + +public class Q3_3_SetOfStacks { + + final int NUM_LIMIT = 3; + + public class SetOfStacks { + + ArrayList> stacks; + + public SetOfStacks() { + stacks = new ArrayList<>(); + //stacks.add(new Stack()); + } + + public int popAt(int target) { + if (target == stacks.size()) { + System.out.println("No Data!!!"); + return Integer.MIN_VALUE; + } + Stack stack = stacks.get(target); + int val = stack.pop(); + shift(target); + return val; + } + + private void shift(int target) { + if (target + 1 < stacks.size()) { + Stack stack = stacks.get(target); + Stack next_stack = stacks.get(target + 1); + stack.push(next_stack.firstElement()); + next_stack.removeElementAt(next_stack.size() - 1); + shift(target + 1); + if (next_stack.isEmpty()) { + stacks.remove(target + 1); + } + } + } + + private Stack getStack() { + if (stacks.isEmpty()) { + return null; + } else { + return stacks.get(stacks.size() - 1); + } + } + + public void push(int e) { + Stack stack = getStack(); + if (stack == null || stack.size() == NUM_LIMIT) { + stack = new Stack<>(); + stacks.add(stack); + } + stack.add(e); + } + + public int pop() { + Stack stack = getStack(); + if (stack == null) { + System.out.println("No Data!!!"); + return Integer.MIN_VALUE; + } + int val = stack.pop(); + if (stack.isEmpty()) { + stacks.remove(stacks.size() - 1); + } + return val; + } + + public int peek() { + Stack stack = getStack(); + if (stack == null) { + System.out.println("No Data!!!"); + return Integer.MIN_VALUE; + } + return stack.peek(); + } + + public void print() { + for (Stack stack : stacks) { + for (int i = 0; i < stack.size(); i++) { + System.out.print(stack.get(i)); + } + System.out.println(); + } + } + } + + public static void main(String[] args) { + Q3_3_SetOfStacks q33 = new Q3_3_SetOfStacks(); + Q3_3_SetOfStacks.SetOfStacks sos = q33.new SetOfStacks(); + for (int i = 0; i < 10; i++) { + sos.push(i); + } + sos.print(); + sos.popAt(1); + sos.print(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_4_Hanoi.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_4_Hanoi.java new file mode 100644 index 0000000..febc461 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_4_Hanoi.java @@ -0,0 +1,62 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 3, 2013 + */ +package CareerCup.StacksAndQueues; + +import LeetCode.OnlineJudge.Q34_StrStr; +import java.util.Stack; + +public class Q3_4_Hanoi { + + public class Hanoi { + + Stack[] stack_list; + + public Hanoi(int n) { + stack_list = new Stack[3]; + for (int i = 0; i < 3; i++) { + stack_list[i] = new Stack<>(); + } + for (int i = 1; i <= n; i++) { + stack_list[0].push(i); + } + } + + public void solve() { + solve(stack_list[0], stack_list[1], stack_list[2], stack_list[0].size()); + } + + public void solve(Stack origin, Stack buffer, Stack destination, int n) { + if (n == 1) { + destination.push(origin.pop()); + return; + } + solve(origin, destination, buffer, n - 1); + destination.push(origin.pop()); + solve(buffer, origin, destination, n - 1); + } + + private void solve(Stack origin, Stack buffer, Stack destination) { + buffer.push(origin.pop()); + destination.push(origin.pop()); + destination.push(buffer.pop()); + } + + public void print() { + for (Stack stack : stack_list) { + for (int i = 0; i < stack.size(); i++) { + System.out.print(stack.get(i)); + } + System.out.println(); + } + } + } + + public static void main(String[] args) { + Q3_4_Hanoi q34 = new Q3_4_Hanoi(); + Q3_4_Hanoi.Hanoi hanoi = q34.new Hanoi(5); + hanoi.print(); + hanoi.solve(); + hanoi.print(); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_5_QueueOn2Stack.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_5_QueueOn2Stack.java new file mode 100644 index 0000000..c5363fe --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_5_QueueOn2Stack.java @@ -0,0 +1,44 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.StacksAndQueues; + +import java.util.Stack; + +public class Q3_5_QueueOn2Stack { + + public class Queue + { + Stack left,right; + + public Queue() + { + left = new Stack<>(); + right = new Stack<>(); + } + + public void enqueue(T val) + { + left.push(val); + } + + public T dequeue() + { + if (right.isEmpty()) { + if (left.isEmpty()) { + System.out.println("No Data!!!"); + return null; + }else{ + while (!left.isEmpty()) { + right.push(left.pop()); + } + } + } + return right.pop(); + } + } + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_6_SortStack.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_6_SortStack.java new file mode 100644 index 0000000..71d129d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_6_SortStack.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.StacksAndQueues; + +import java.util.Stack; + +public class Q3_6_SortStack { + + private Stack Helper = new Stack<>(); + + public void sort(Stack stack) { + while (true) { + while (Helper.isEmpty() || (!stack.isEmpty() && Helper.peek() <= stack.peek())) { + Helper.push(stack.pop()); + } + if (stack.isEmpty()) { + break; + } else { + int val = stack.pop(); + while (!Helper.isEmpty()) { + stack.push(Helper.pop()); + } + stack.push(val); + } + } + while (!Helper.isEmpty()) { + stack.push(Helper.pop()); + } + } + + public static void main(String[] args) { + Stack stack = new Stack<>(); + stack.push(2); + stack.push(5); + stack.push(4); + stack.push(3); + stack.push(6); + stack.push(1); + Q3_6_SortStack q36 = new Q3_6_SortStack(); + q36.sort(stack); + for (int i = 0; i < stack.size(); i++) { + System.out.println(stack.get(i)); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_7_AnimalQueue.java b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_7_AnimalQueue.java new file mode 100644 index 0000000..445de32 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/StacksAndQueues/Q3_7_AnimalQueue.java @@ -0,0 +1,68 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.StacksAndQueues; + +import java.util.LinkedList; + +public class Q3_7_AnimalQueue { + + public abstract class Animal { + + public String name; + public int order; + } + + public class Dog extends Animal { + } + + public class Cat extends Animal { + } + + public class AnimalQueue { + + LinkedList dogs = new LinkedList<>(); + LinkedList cats = new LinkedList<>(); + private int order = 0; + + public void enqueue(Animal animal) { + animal.order = this.order++; + if (animal instanceof Dog) { + dogs.add((Dog) animal); + } else if (animal instanceof Cat) { + cats.add((Cat) animal); + } + } + + public Cat dequeueCat() { + return cats.poll(); + } + + public Dog dequeueDog() { + return dogs.poll(); + } + + public Animal dequeue() { + if (dogs.isEmpty()) { + return dequeueCat(); + } else if (cats.isEmpty()) { + return dequeueDog(); + } + if (dogs.peek().order < cats.peek().order) { + return dequeueDog(); + } else { + return dequeueCat(); + } + } + } + + public static void main(String[] args) { + LinkedList ll = new LinkedList<>(); + ll.add('a'); + ll.add('b'); + ll.add('c'); + ll.add('d'); + ll.add('e'); + System.out.println(ll.pollLast()); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/App.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/App.java new file mode 100644 index 0000000..e205d03 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/App.java @@ -0,0 +1,19 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_3_ChopStick; + +public class App { + + public static void main(String[] args) { + Chopstick left = new Chopstick(); + Chopstick right = new Chopstick(); + Philosopher philosophers[] = new Philosopher[10]; + for (int i = 0; i < 10; i++) { + philosophers[i] = new Philosopher(left, right, i + 1); + } + for (int i = 0; i < 10; i++) { + philosophers[i].start(); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/Chopstick.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/Chopstick.java new file mode 100644 index 0000000..e8d4a0f --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/Chopstick.java @@ -0,0 +1,27 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_3_ChopStick; + +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.Lock; + +public class Chopstick { + + Lock lock; + + public Chopstick() { + lock = new ReentrantLock(); + } + + public boolean pickUp() { + return lock.tryLock(); + } + + public void putDown() { + lock.unlock(); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/Philosopher.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/Philosopher.java new file mode 100644 index 0000000..28348ed --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_3_ChopStick/Philosopher.java @@ -0,0 +1,71 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_3_ChopStick; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Philosopher extends Thread { + + private Chopstick LeftStick; + private Chopstick RightStick; + int index; + + public Philosopher(Chopstick _left, Chopstick _right, int index) { + this.LeftStick = _left; + this.RightStick = _right; + this.index = index; + } + + public boolean pickUp() { + if (!LeftStick.pickUp()) { + return false; + } + if (!RightStick.pickUp()) { + LeftStick.putDown(); + return false; + } + return true; + } + + public void putDown() { + System.out.println(index + " put down!"); + LeftStick.putDown(); + RightStick.putDown(); + } + + public void chew() { + System.out.println(index + "Chew!"); + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + System.out.println("Sleep:" + ex.getMessage()); + //Logger.getLogger(Philosopher.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void eat() { + if (pickUp()) { + chew(); + putDown(); + System.out.println(index + " success to pick up."); + } else { + try { + //System.out.println(index + " fail to pick up."); + Thread.sleep(1000); + eat(); + } catch (InterruptedException ex) { + } + + } + } + + @Override + public void run() { + eat(); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/Foo.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/Foo.java new file mode 100644 index 0000000..2fed292 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/Foo.java @@ -0,0 +1,58 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_5_Foo; + +import java.util.concurrent.Semaphore; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Foo { + + public static Semaphore sp1, sp2, sp3; + + public Foo() { + try { + sp1 = new Semaphore(1); + sp2 = new Semaphore(1); + sp3 = new Semaphore(1); + + sp1.acquire(); + sp2.acquire(); + sp3.acquire(); + } catch (InterruptedException ex) { + ex.printStackTrace(); + //Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void first() { + System.out.println("first"); + sp1.release(); + } + + public void second() { + try { + sp1.acquire(); + sp1.release(); + System.out.println("second"); + sp2.release(); + } catch (InterruptedException ex) { + Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void third() { + try { + sp2.acquire(); + sp2.release(); + System.out.println("third"); + sp3.release(); + } catch (InterruptedException ex) { + Logger.getLogger(Foo.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooLock.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooLock.java new file mode 100644 index 0000000..3858a0b --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooLock.java @@ -0,0 +1,60 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_5_Foo; + +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FooLock extends Thread { + + public ReentrantLock lock1, lock2, lock3; + + public FooLock() { + if (lock1 == null) { + lock1 = new ReentrantLock(); + } + if (lock2 == null) { + lock2 = new ReentrantLock(); + lock2.lock(); + } + if (lock3 == null) { + lock3 = new ReentrantLock(); + lock3.lock(); + } + } + + public boolean first() throws InterruptedException { + if (lock1.isLocked()) { + Thread.sleep(10000); + first(); + } + System.out.println("first"); + lock2.unlock(); + return false; + } + + public boolean second() throws InterruptedException { + if (lock2.isLocked()) { + Thread.sleep(10000); + second(); + + } + System.out.println("second"); + lock3.unlock(); + return false; + } + + public boolean third() throws InterruptedException { + if (lock3.isLocked()) { + Thread.sleep(10000); + third(); + } + System.out.println("third"); + return false; + } + + public static void main(String[] args) throws InterruptedException { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooLockThread.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooLockThread.java new file mode 100644 index 0000000..2fb87f1 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooLockThread.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_5_Foo; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class FooLockThread extends Thread { + + int i; + FooLock fl; + + public FooLockThread(int i) { + this.i = i; + fl = new FooLock(); + } + + @Override + public void run() { + try { + switch (i) { + case 1: + + fl.first(); + + break; + case 2: + fl.second(); + break; + case 3: + fl.third(); + break; + } + } catch (InterruptedException ex) { + Logger.getLogger(FooLockThread.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public static void main(String[] args) { + for (int i = 0; i < 3; i++) { + FooLockThread flt = new FooLockThread(i + 1); + flt.start(); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooThread.java b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooThread.java new file mode 100644 index 0000000..d3341b2 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/ThreadsAndLocks/Q16_5_Foo/FooThread.java @@ -0,0 +1,37 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 27, 2012 + */ +package CareerCup.ThreadsAndLocks.Q16_5_Foo; + +public class FooThread extends Thread { + + Foo f; + int i; + + public FooThread(int i) { + f = new Foo(); + this.i = i; + } + + @Override + public void run() { + switch (i) { + case 1: + f.first(); + break; + case 2: + f.second(); + break; + case 3: + f.third(); + break; + } + } + + public static void main(String[] args) { + for (int i = 0; i < 3; i++) { + FooThread th = new FooThread(i + 1); + th.start(); + } + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/CompleteTree.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/CompleteTree.java new file mode 100644 index 0000000..2067db9 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/CompleteTree.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Mar 17, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class CompleteTree { + + //level init as 0 + public boolean verify(BinaryTreeNode root, int level) { + if (root == null) { + return true; + } + boolean l = verify(root.Left, level + 1); + if (!l) { + return false; + } + boolean r = verify(root.Right, level + 1); + if (!r) { + return false; + } + if (root.Left == null || root.Right == null) { + if (MaxLevel == -1) { + MaxLevel = level; + } else { + if (MaxLevel == level && !LoopFlag) { + return true; + } else if (MaxLevel - 1 == level) { + LoopFlag = true; + return true; + } else { + return false; + } + } + } + return l && r; + } + static int MaxLevel = -1; + static boolean LoopFlag = false; + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree5(); + boolean result = new CompleteTree().verify(root, 0); + System.out.println(result); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q1_3_BuildTree.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q1_3_BuildTree.java new file mode 100644 index 0000000..222350d --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q1_3_BuildTree.java @@ -0,0 +1,23 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class Q1_3_BuildTree { + + public BinaryTreeNode build(int[] arr, int s, int e) { + if (s > e) { + return null; + } + int m = s + (e - s) / 2; + BinaryTreeNode root = new BinaryTreeNode<>(arr[m]); + root.Left = build(arr, s, m - 1); + root.Right = build(arr, m + 1, e); + return root; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_1_IsBalanceTree.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_1_IsBalanceTree.java new file mode 100644 index 0000000..c65188a --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_1_IsBalanceTree.java @@ -0,0 +1,40 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import LeetCode.OnlineJudge.Q41_LengthOfLastWord; +import Util.BinaryTreeNode; + +public class Q4_1_IsBalanceTree { + + public boolean isBalance(BinaryTreeNode root) { + int dif = isBalanceHelper(root); + return dif != -1; + } + + public int isBalanceHelper(BinaryTreeNode root) { + if (root == null) { + return 0; + } + int l = isBalanceHelper(root.Left); + if (l == -1) { + return -1; + } + int r = isBalanceHelper(root.Right); + if (r == -1) { + return -1; + } + int dif = Math.abs(l - r); + if (dif > 2) { + return -1; + } + return dif + 1; + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + Q4_1_IsBalanceTree q41 = new Q4_1_IsBalanceTree(); + System.out.println(q41.isBalanceHelper(root)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_2_BFSOnGraph.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_2_BFSOnGraph.java new file mode 100644 index 0000000..7f6cc89 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_2_BFSOnGraph.java @@ -0,0 +1,42 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import LeetCode.OnlineJudge.Q42_LetterCombinationPhoneNum; +import Util.GraphNode; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class Q4_2_BFSOnGraph { + + public boolean isConnect(GraphNode root) { + Queue> q = new LinkedList<>(); + q.add(root); + while (!q.isEmpty()) { + GraphNode cur = q.poll(); + cur.state = 1; + ArrayList> nodes = cur.Nodes; + for (GraphNode node : nodes) { + if (node.state == 1) { + System.out.println(node.Data); + return false; + } else if (node.state == 0) { + q.add(node); + } else { + System.out.println("ERROR"); + } + } + } + return true; + } + + public static void main(String[] args) { + GraphNode root1 = GraphNode.getSampleGraphNode(); + GraphNode root2 = GraphNode.getSampleGraphNode2(); + Q4_2_BFSOnGraph q42 = new Q4_2_BFSOnGraph(); + q42.isConnect(root1); + q42.isConnect(root2); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_4_CreateLevelList.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_4_CreateLevelList.java new file mode 100644 index 0000000..8e49873 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_4_CreateLevelList.java @@ -0,0 +1,76 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class Q4_4_CreateLevelList { + + public ArrayList>> getLevelList2(BinaryTreeNode root) { + ArrayList>> solution = new ArrayList<>(); + getLevelList2Helper(solution, 0, root); + return solution; + } + + private void getLevelList2Helper(ArrayList>> solution, int level, BinaryTreeNode root) { + LinkedList> list = null; + if (level >= solution.size()) { + list = new LinkedList<>(); + solution.add(list); + } else { + list = solution.get(level); + } + list.add(root); + if (root.Left != null) { + getLevelList2Helper(solution, 1 + level, root.Left); + } + if (root.Right != null) { + getLevelList2Helper(solution, 1 + level, root.Right); + } + } + + public ArrayList>> getLevelList(BinaryTreeNode root) { + ArrayList>> solution = new ArrayList<>(); + LinkedList> list = new LinkedList<>(); + if (root != null) { + list.add(root); + solution.add(list); + } + while (!list.isEmpty()) { + LinkedList> next_list = new LinkedList<>(); + for (int i = 0; i < list.size(); i++) { + BinaryTreeNode cur = list.get(i); + if (cur.Left != null) { + next_list.add(cur.Left); + } + if (cur.Right != null) { + next_list.add(cur.Right); + } + } + list = next_list; + solution.add(list); + } + return solution; + } + + public static void main(String[] args) { + Q4_4_CreateLevelList q44 = new Q4_4_CreateLevelList(); + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + ArrayList>> solution = q44.getLevelList2(root); + print(solution); + } + + private static void print(ArrayList>> solution) { + for (LinkedList> list : solution) { + for (BinaryTreeNode binaryTreeNode : list) { + System.out.print(binaryTreeNode.Data + " "); + } + System.out.println();; + } + + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_5_ValidBinarySearchTree.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_5_ValidBinarySearchTree.java new file mode 100644 index 0000000..0a69c46 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_5_ValidBinarySearchTree.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class Q4_5_ValidBinarySearchTree { + + public boolean isSearchTreeS(BinaryTreeNode root, int min, int max) { + if (root == null) { + return true; + } + if (root.Data > min || root.Data < max) { + return false; + } + boolean result = true; + result &= isSearchTreeS(root.Right, root.Data, max) && isSearchTreeS(root.Left, min, root.Data); + return result; + } + + public boolean isSearchTree(BinaryTreeNode root, int min, int max) { + if (root == null) { + return true; + } + if (root.Left != null) { + if (min > root.Left.Data || root.Data < root.Left.Data) { + return false; + } + } else if (root.Right != null) { + if (max < root.Right.Data || root.Data > root.Right.Data) { + return false; + } + } + boolean result = true; + result &= isSearchTree(root.Right, root.Data, max) && isSearchTree(root.Left, min, root.Data); + return result; + } + + public static void main(String[] args) { + BinaryTreeNode bstree = BinaryTreeNode.getSampleTree(); + BinaryTreeNode ubstree = BinaryTreeNode.getSampleTree2(); + Q4_5_ValidBinarySearchTree q45 = new Q4_5_ValidBinarySearchTree(); + System.out.println(q45.isSearchTree(bstree, Integer.MIN_VALUE, Integer.MAX_VALUE)); + System.out.println(q45.isSearchTree(ubstree, Integer.MIN_VALUE, Integer.MAX_VALUE)); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_6_NextNode.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_6_NextNode.java new file mode 100644 index 0000000..340ddbd --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_6_NextNode.java @@ -0,0 +1,33 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class Q4_6_NextNode { + + public BinaryTreeNode next(BinaryTreeNode node) { + BinaryTreeNode runner = node; + if (runner.Right != null) { + runner = runner.Right; + while (runner.Left != null) { + runner = runner.Left; + } + return runner; + }else{ + BinaryTreeNode parent = runner.Parent; + while (parent.Left == runner) { + runner = parent; + parent = runner.Parent; + } + return parent; + } + } + + public static void main(String[] args) { + BinaryTreeNode node = BinaryTreeNode.getSampleTree(); + Q4_6_NextNode q46 = new Q4_6_NextNode(); + System.out.println(q46.next(node).Data); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_7_CommonAncester.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_7_CommonAncester.java new file mode 100644 index 0000000..0ad0740 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_7_CommonAncester.java @@ -0,0 +1,75 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class Q4_7_CommonAncester { + + public BinaryTreeNode find(BinaryTreeNode root, BinaryTreeNode p, BinaryTreeNode q) { + Wrapper wr = findHelper(root, p, q); + if (wr.find) { + return wr.node; + } else { + return null; + } + } + + public Wrapper findHelper(BinaryTreeNode root, BinaryTreeNode p, BinaryTreeNode q) { + Wrapper wr = new Wrapper(); + if (root == null) { + if (p == root) { + wr.node = p; + } else if (q == root) { + wr.node = q; + } + return wr; + } + Wrapper l = findHelper(root.Left, p, q); + if (l.find) { + return l; + } + Wrapper r = findHelper(root.Right, p, q); + if (r.find) { + return r; + } + if (l.node != null && r.node != null) { + wr.node = root; + wr.find = true; + return wr; + } else if (root == p || root == q) { + wr.find = l.node != null || r.node != null; + wr.node = root; + } else { + wr.find = false; + if (p == root) { + wr.node = p; + } else if (q == root) { + wr.node = q; + } + } + return wr; + } + + class Wrapper { + + BinaryTreeNode node; + boolean find; + + public Wrapper() { + } + + public Wrapper(BinaryTreeNode _node, boolean _find) { + this.node = _node; + this.find = _find; + } + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + Q4_7_CommonAncester q47 = new Q4_7_CommonAncester(); + BinaryTreeNode ancester = q47.find(root, root.Left.Left, root.Left); + System.out.println(ancester.Data); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_8_SubTree.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_8_SubTree.java new file mode 100644 index 0000000..884a4f4 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_8_SubTree.java @@ -0,0 +1,65 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class Q4_8_SubTree { + + public boolean isSubtree(BinaryTreeNode large, BinaryTreeNode small) { + if (large == null || small == null) { + return false; + } + boolean result = false; + if (large.Data == small.Data) { + result |= match(large, small); + //alternative + if (match(large, small)) { + return true; + } + //alternative + } + boolean l = isSubtree(large.Left, small); + if (l) { + return l; + } + boolean r = isSubtree(large.Right, small); + if (r) { + return r; + } + return result; + } + + private boolean match(BinaryTreeNode large, BinaryTreeNode small) { + if (large == null && small == null) { + return true; + } else if (large == null) { + return false; + } else if (small == null) { + return true; + } + boolean result = true; + boolean l = match(large.Left, small.Left); + if (!l) { + return l; + } + boolean r = match(large.Right, small.Right); + if (!r) { + return r; + } + if (large.Data != small.Data) { + return false; + } + return result; + } + + public static void main(String[] args) { + BinaryTreeNode large = BinaryTreeNode.getSampleTree(); + BinaryTreeNode small = large.Left; + BinaryTreeNode small2 = BinaryTreeNode.getSampleTree2(); + Q4_8_SubTree q48 = new Q4_8_SubTree(); + boolean result = q48.isSubtree(large, small2); + System.out.println(result); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_9_FindSum.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_9_FindSum.java new file mode 100644 index 0000000..c014944 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/Q4_9_FindSum.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 5, 2013 + */ +package CareerCup.TreesAndGraphs; + +import Util.BinaryTreeNode; + +public class Q4_9_FindSum { + + private int[] array; + + public void findsum(BinaryTreeNode root, int sum) { + array = new int[root.getHeight()]; + findsumHelper(root, sum, 0); + } + + public void findsumHelper(BinaryTreeNode root, int sum, int level) { + if (root == null) { + return; + } + array[level] = root.Data; + int count = sum; + for (int i = level; i >= 0; --i) { + count -= array[i]; + if (count == 0) { + print(array, i, level); + } + } + findsumHelper(root.Left, sum, level + 1); + findsumHelper(root.Right, sum, level + 1); + + } + + private void print(int[] array, int s, int e) { + for (int i = s; i <= e; i++) { + System.out.print(array[i] + " "); + } + System.out.println(); + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + Q4_9_FindSum q49 = new Q4_9_FindSum(); + q49.findsum(root, 17); + } +} diff --git a/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/RedBlackTree.java b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/RedBlackTree.java new file mode 100644 index 0000000..1b29721 --- /dev/null +++ b/Algorithm-Java-Backup/src/CareerCup/TreesAndGraphs/RedBlackTree.java @@ -0,0 +1,581 @@ +package CareerCup.TreesAndGraphs; + +import java.util.*; + +public class RedBlackTree +{ + //������������ɫ + private static final boolean RED = false; + private static final boolean BLACK = true; + static class Node + { + Object data; + Node parent; + Node left; + Node right; + //�ڵ��Ĭ����ɫ�Ǻ�ɫ + boolean color = BLACK; + public Node(Object data , Node parent + , Node left , Node right) + { + this.data = data; + this.parent = parent; + this.left = left; + this.right = right; + } + public String toString() + { + return "[data=" + data + + ", color=" + color + "]"; + } + public boolean equals(Object obj) + { + if (this == obj) + { + return true; + } + if (obj.getClass() == Node.class) + { + Node target = (Node)obj; + return data.equals(target.data) + && color == target.color + && left == target.left + && right == target.right + && parent == target.parent; + } + return false; + } + } + private Node root; + //�������������ڴ������������ + public RedBlackTree() + { + root = null; + } + public RedBlackTree(T o) + { + root = new Node(o , null , null , null); + } + //��ӽڵ� + public void add(T ele) + { + //����ڵ�Ϊnull + if (root == null) + { + root = new Node(ele , null , null , null); + } + else + { + Node current = root; + Node parent = null; + int cmp = 0; + //�������ʵ�Ҷ�ӽڵ㣬�Ը�Ҷ�ӽڵ�Ϊ���ڵ�����½ڵ� + do + { + parent = current; + cmp = ele.compareTo(current.data); + //����½ڵ��ֵ���ڵ�ǰ�ڵ��ֵ + if (cmp > 0) + { + //�����ӽڵ���Ϊ��ǰ�ڵ� + current = current.right; + } + //����½ڵ��ֵС�ڵ�ǰ�ڵ��ֵ + else + { + //�����ӽڵ���Ϊ��ǰ�ڵ� + current = current.left; + } + } + while (current != null); + //�����½ڵ� + Node newNode = new Node(ele , parent , null , null); + //����½ڵ��ֵ���ڸ��ڵ��ֵ + if (cmp > 0) + { + //�½ڵ���Ϊ���ڵ�����ӽڵ� + parent.right = newNode; + } + //����½ڵ��ֵС�ڸ��ڵ��ֵ + else + { + //�½ڵ���Ϊ���ڵ�����ӽڵ� + parent.left = newNode; + } + //ά������� + fixAfterInsertion(newNode); + } + } + //ɾ��ڵ� + public void remove(T ele) + { + //��ȡҪɾ��Ľڵ� + Node target = getNode(ele); + //���ɾ��ڵ��������������������Ϊ�� + if (target.left != null && target.right != null) + { + //�ҵ�target�ڵ���������ǰһ���ڵ� + //s���ڱ���target�ڵ����������ֵ���Ľڵ� + Node s = target.left; + //����target�ڵ����������ֵ���Ľڵ� + while (s.right != null) + { + s = s.right; + } + //��s�ڵ�������p�ڵ� + target.data = s.data; + target = s; + } + //��ʼ�޸�����滻�ڵ㣬�����滻�ڵ㲻Ϊnull + Node replacement = (target.left != null ? target.left : target.right); + if (replacement != null) + { + // ��replacement��parentָ��target��parent + replacement.parent = target.parent; + //���target��parentΪnull������target�����Ǹ�ڵ� + if (target.parent == null) + { + root = replacement; + } + //���target���丸�ڵ�����ӽڵ� + else if (target == target.parent.left) + { + //��target�ĸ��ڵ�leftָ��replacement + target.parent.left = replacement; + } + //���target���丸�ڵ�����ӽڵ� + else + { + //��target�ĸ��ڵ�rightָ��replacement + target.parent.right = replacement; + } + //����ɾ��target�ڵ� + target.left = target.right = target.parent = null; + + // �޸������ + if (target.color == BLACK) + { + fixAfterDeletion(replacement); + } + } + //target�����Ǹ�ڵ� + else if (target.parent == null) + { + root = null; + } + else + { + //targetû���ӽڵ㣬���������滻�ڵ㡣 + //�޸������ + if (target.color == BLACK) + { + fixAfterDeletion(target); + } + if (target.parent != null) + { + //���target���丸�ڵ�����ӽڵ� + if (target == target.parent.left) + { + //��target�ĸ��ڵ�left��Ϊnull + target.parent.left = null; + } + //���target���丸�ڵ�����ӽڵ� + else if (target == target.parent.right) + { + //��target�ĸ��ڵ�right��Ϊnull + target.parent.right = null; + } + //��target��parent����null + target.parent = null; + } + } + } + //��ݸ��ֵ�����ڵ� + public Node getNode(T ele) + { + //�Ӹ�ڵ㿪ʼ���� + Node p = root; + while (p != null) + { + int cmp = ele.compareTo(p.data); + //���������ֵС�ڵ�ǰp�ڵ��ֵ + if (cmp < 0) + { + //������������ + p = p.left; + } + //���������ֵ���ڵ�ǰp�ڵ��ֵ + else if (cmp > 0) + { + //������������ + p = p.right; + } + else + { + return p; + } + } + return null; + } + //������ȱ��� + public List breadthFirst() + { + Queue queue = new ArrayDeque(); + List list = new ArrayList(); + if( root != null) + { + //����Ԫ���롰���С� + queue.offer(root); + } + while(!queue.isEmpty()) + { + //���ö��еġ���β����Ԫ����ӵ�List�� + list.add(queue.peek()); + Node p = queue.poll(); + //������ӽڵ㲻Ϊnull�������롰���С� + if(p.left != null) + { + queue.offer(p.left); + } + //������ӽڵ㲻Ϊnull�������롰���С� + if(p.right != null) + { + queue.offer(p.right); + } + } + return list; + } + //����ڵ���޸������ + private void fixAfterInsertion(Node x) + { + x.color = RED; + //ֱ��x�ڵ�ĸ��ڵ㲻�Ǹ���x�ĸ��ڵ㲻�Ǻ�ɫ + while (x != null && x != root + && x.parent.color == RED) + { + //���x�ĸ��ڵ����丸�ڵ�����ӽڵ� + if (parentOf(x) == leftOf(parentOf(parentOf(x)))) + { + //��ȡx�ĸ��ڵ���ֵܽڵ� + Node y = rightOf(parentOf(parentOf(x))); + //���x�ĸ��ڵ���ֵܽڵ��Ǻ�ɫ + if (colorOf(y) == RED) + { + //��x�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), BLACK); + //��x�ĸ��ڵ���ֵܽڵ���Ϊ��ɫ + setColor(y, BLACK); + //��x�ĸ��ڵ�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(parentOf(x)), RED); + x = parentOf(parentOf(x)); + } + //���x�ĸ��ڵ���ֵܽڵ��Ǻ�ɫ + else + { + //���x���丸�ڵ�����ӽڵ� + if (x == rightOf(parentOf(x))) + { + //��x�ĸ��ڵ���Ϊx + x = parentOf(x); + rotateLeft(x); + } + //��x�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), BLACK); + //��x�ĸ��ڵ�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(parentOf(x)), RED); + rotateRight(parentOf(parentOf(x))); + } + } + //���x�ĸ��ڵ����丸�ڵ�����ӽڵ� + else + { + //��ȡx�ĸ��ڵ���ֵܽڵ� + Node y = leftOf(parentOf(parentOf(x))); + //���x�ĸ��ڵ���ֵܽڵ��Ǻ�ɫ + if (colorOf(y) == RED) + { + //��x�ĸ��ڵ���Ϊ��ɫ�� + setColor(parentOf(x), BLACK); + //��x�ĸ��ڵ���ֵܽڵ���Ϊ��ɫ + setColor(y, BLACK); + //��x�ĸ��ڵ�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(parentOf(x)), RED); + //��x��Ϊx�ĸ��ڵ�Ľڵ� + x = parentOf(parentOf(x)); + } + //���x�ĸ��ڵ���ֵܽڵ��Ǻ�ɫ + else + { + //���x���丸�ڵ�����ӽڵ� + if (x == leftOf(parentOf(x))) + { + //��x�ĸ��ڵ���Ϊx + x = parentOf(x); + rotateRight(x); + } + //��x�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), BLACK); + //��x�ĸ��ڵ�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(parentOf(x)), RED); + rotateLeft(parentOf(parentOf(x))); + } + } + } + //����ڵ���Ϊ��ɫ + root.color = BLACK; + } + //ɾ��ڵ���޸������ + private void fixAfterDeletion(Node x) + { + //ֱ��x���Ǹ�ڵ㣬��x����ɫ�Ǻ�ɫ + while (x != root && colorOf(x) == BLACK) + { + //���x���丸�ڵ�����ӽڵ� + if (x == leftOf(parentOf(x))) + { + //��ȡx�ڵ���ֵܽڵ� + Node sib = rightOf(parentOf(x)); + //���sib�ڵ��Ǻ�ɫ + if (colorOf(sib) == RED) + { + //��sib�ڵ���Ϊ��ɫ + setColor(sib, BLACK); + //��x�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), RED); + rotateLeft(parentOf(x)); + //�ٴν�sib��Ϊx�ĸ��ڵ�����ӽڵ� + sib = rightOf(parentOf(x)); + } + //���sib�������ӽڵ㶼�Ǻ�ɫ + if (colorOf(leftOf(sib)) == BLACK + && colorOf(rightOf(sib)) == BLACK) + { + //��sib��Ϊ��ɫ + setColor(sib, RED); + //��x����x�ĸ��ڵ� + x = parentOf(x); + } + else + { + //���sib��ֻ�����ӽڵ��Ǻ�ɫ + if (colorOf(rightOf(sib)) == BLACK) + { + //��sib�����ӽڵ�Ҳ��Ϊ��ɫ + setColor(leftOf(sib), BLACK); + //��sib��Ϊ��ɫ + setColor(sib, RED); + rotateRight(sib); + sib = rightOf(parentOf(x)); + } + //����sib����ɫ��x�ĸ��ڵ����ɫ��ͬ + setColor(sib, colorOf(parentOf(x))); + //��x�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), BLACK); + //��sib�����ӽڵ���Ϊ��ɫ + setColor(rightOf(sib), BLACK); + rotateLeft(parentOf(x)); + x = root; + } + } + //���x���丸�ڵ�����ӽڵ� + else + { + //��ȡx�ڵ���ֵܽڵ� + Node sib = leftOf(parentOf(x)); + //���sib����ɫ�Ǻ�ɫ + if (colorOf(sib) == RED) + { + //��sib����ɫ��Ϊ��ɫ + setColor(sib, BLACK); + //��sib�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), RED); + rotateRight(parentOf(x)); + sib = leftOf(parentOf(x)); + } + //���sib�������ӽڵ㶼�Ǻ�ɫ + if (colorOf(rightOf(sib)) == BLACK + && colorOf(leftOf(sib)) == BLACK) + { + //��sib��Ϊ��ɫ + setColor(sib, RED); + //��x����x�ĸ��ڵ� + x = parentOf(x); + } + else + { + //���sibֻ�����ӽڵ��Ǻ�ɫ + if (colorOf(leftOf(sib)) == BLACK) + { + //��sib�����ӽڵ�Ҳ��Ϊ��ɫ + setColor(rightOf(sib), BLACK); + //��sib��Ϊ��ɫ + setColor(sib, RED); + rotateLeft(sib); + sib = leftOf(parentOf(x)); + } + //��sib����ɫ��Ϊ��x�ĸ��ڵ���ɫ��ͬ + setColor(sib, colorOf(parentOf(x))); + //��x�ĸ��ڵ���Ϊ��ɫ + setColor(parentOf(x), BLACK); + //��sib�����ӽڵ���Ϊ��ɫ + setColor(leftOf(sib), BLACK); + rotateRight(parentOf(x)); + x = root; + } + } + } + setColor(x, BLACK); + } + //��ȡָ���ڵ����ɫ + private boolean colorOf(Node p) + { + return (p == null ? BLACK : p.color); + } + //��ȡָ���ڵ�ĸ��ڵ� + private Node parentOf(Node p) + { + return (p == null ? null: p.parent); + } + //Ϊָ���ڵ�������ɫ + private void setColor(Node p, boolean c) + { + if (p != null) + { + p.color = c; + } + } + //��ȡָ���ڵ�����ӽڵ� + private Node leftOf(Node p) + { + return (p == null) ? null: p.left; + } + //��ȡָ���ڵ�����ӽڵ� + private Node rightOf(Node p) + { + return (p == null) ? null: p.right; + } + /** + * ִ������ת�� + * p r + * r p + * q q + */ + private void rotateLeft(Node p) + { + if (p != null) + { + //ȡ��p�����ӽڵ� + Node r = p.right; + Node q = r.left; + //��r�����ӽڵ�����p���ҽڵ����� + p.right = q; + //��r�����ӽڵ��parentָ��p�ڵ� + if (q != null) + { + q.parent = p; + } + r.parent = p.parent; + //���p�Ѿ��Ǹ�ڵ� + if (p.parent == null) + { + root = r; + } + //���p���丸�ڵ�����ӽڵ� + else if (p.parent.left == p) + { + //��r��Ϊp�ĸ��ڵ�����ӽڵ� + p.parent.left = r; + } + else + { + //��r��Ϊp�ĸ��ڵ�����ӽڵ� + p.parent.right = r; + } + r.left = p; + p.parent = r; + } + } + /** + * ִ������ת�� + * p l + * l p + * q q + */ + private void rotateRight(Node p) + { + if (p != null) + { + //ȡ��p�����ӽڵ� + Node l = p.left; + Node q = l.right; + //��l�����ӽڵ�����p����ڵ����� + p.left = q; + //��l�����ӽڵ��parentָ��p�ڵ� + if (q != null) + { + q.parent = p; + } + l.parent = p.parent; + //���p�Ѿ��Ǹ�ڵ� + if (p.parent == null) + { + root = l; + } + //���p���丸�ڵ�����ӽڵ� + else if (p.parent.right == p) + { + //��l��Ϊp�ĸ��ڵ�����ӽڵ� + p.parent.right = l; + } + else + { + //��l��Ϊp�ĸ��ڵ�����ӽڵ� + p.parent.left = l; + } + l.right = p; + p.parent = l; + } + } + //ʵ��������� + public List inIterator() + { + return inIterator(root); + } + private List inIterator(Node node) + { + List list = new ArrayList(); + //�ݹ鴦�������� + if (node.left != null) + { + list.addAll(inIterator(node.left)); + } + //�����ڵ� + list.add(node); + //�ݹ鴦�������� + if (node.right != null) + { + list.addAll(inIterator(node.right)); + } + return list; + } + + public static void main(String[] args) + { + RedBlackTree tree + = new RedBlackTree(); + //��ӽڵ� + tree.add(5); + tree.add(20); + tree.add(10); + tree.add(3); + tree.add(8); + tree.add(15); + tree.add(30); + System.out.println(tree.breadthFirst()); + //ɾ��ڵ� + tree.remove(20); + System.out.println(tree.breadthFirst()); +// System.out.println(tree.inIterator()); + + } +} diff --git a/Algorithm-Linux/.DS_Store b/Algorithm-Java-Backup/src/LeetCode/.DS_Store similarity index 91% rename from Algorithm-Linux/.DS_Store rename to Algorithm-Java-Backup/src/LeetCode/.DS_Store index 5008ddf..3f28d28 100644 Binary files a/Algorithm-Linux/.DS_Store and b/Algorithm-Java-Backup/src/LeetCode/.DS_Store differ diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q100_SpiralMatrix.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q100_SpiralMatrix.java new file mode 100644 index 0000000..61a8d5c --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q100_SpiralMatrix.java @@ -0,0 +1,137 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q100_SpiralMatrix { + + public ArrayList spiralOrder(int[][] matrix) { + ArrayList solution = new ArrayList<>(); + int m = matrix.length - 1, n = matrix[0].length - 1; + for (int i = 0; i <= Math.min(m, n) / 2; i++) { + for (int col = i; col <= n - i; col++) { + solution.add(matrix[i][col]); + } + for (int row = i + 1; row <= m - i; row++) { + solution.add(matrix[row][n - i]); + } + if (m - i * 2 > 0) { + for (int col = n - i - 1; col >= i; col--) { + solution.add(matrix[m - i][col]); + } + } + if (n - i * 2 > 0) { + for (int row = m - i - 1; row > i; row--) { + solution.add(matrix[row][i]); + } + } + } + return solution; + } + + public ArrayList spiralOrderEx(int[][] matrix) { + ArrayList solution = new ArrayList<>(); + int height = matrix.length, width = matrix[0].length; + int col = 0, row = 0; + int h = height, w = width; + boolean GoRight = true, GoDown = false, GoLeft = false, GoUp = false; + solution.add(matrix[0][0]); + while (col <= h && row <= w) { + int pre_row = row; + while (GoRight) { + ++row; + if (row >= w) { + if (row - 1 == pre_row) { + break; + } + row = w - 1; + GoRight = false; + GoDown = true; + } else { + solution.add(matrix[col][row]); + } + } + int pre_col = col; + while (GoDown) { + ++col; + if (col >= h) { + if (col - 1 == pre_col) { + break; + } + col = h - 1; + GoDown = false; + GoLeft = true; + } else { + solution.add(matrix[col][row]); + } + } + while (GoLeft) { + --row; + if (row < width - w) { + row = width - w; + GoLeft = false; + GoUp = true; + } else { + solution.add(matrix[col][row]); + } + } + while (GoUp) { + --col; + if (col <= height - h) { + col = height - h + 1; + GoUp = false; + GoRight = true; + } else { + solution.add(matrix[col][row]); + } + } + w -= 1; + h -= 1; + } + return solution; + } + + public static void main(String[] args) { + int matrix[][] = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12} + }; + ArrayList solution = new Q100_SpiralMatrix().spiralOrderMy(matrix, 0, 0, matrix[0].length, matrix.length); + for (Integer integer : solution) { + System.out.print(integer + " "); + } + System.out.println(); + ArrayList solution2 = new Q100_SpiralMatrix().spiralOrder(matrix); + for (Integer integer : solution2) { + System.out.print(integer + " "); + } + } + + public ArrayList spiralOrderMy(int[][] matrix, int col, int row, int width, int height) { + ArrayList solution = new ArrayList<>(); + if (width <= 0 || height <= 0) { + return solution; + } + for (int i = 0; i < width; i++) { + solution.add(matrix[col][row + i]); + } + for (int i = 1; i < height; i++) { + solution.add(matrix[col + i][row + width - 1]); + } + if (height > 1) { + for (int i = 1; i < width; i++) { + solution.add(matrix[col + height - 1][row + width - 1 - i]); + } + } + if (width > 1) { + for (int i = 1; i < height - 1; i++) { + solution.add(matrix[col + height - 1 - i][row]); + } + } + solution.addAll(spiralOrderMy(matrix, col + 1, row + 1, width - 2, height - 2)); + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q101_SpiralMatrix2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q101_SpiralMatrix2.java new file mode 100644 index 0000000..7df69d4 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q101_SpiralMatrix2.java @@ -0,0 +1,88 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +import java.io.FileWriter; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Q101_SpiralMatrix2 { + + public int[][] generateMatrix(int n) { + int matrix[][] = new int[n][n]; + int i, col, row, edge = n - 1, num = 1; + for (i = 0; i <= edge / 2; i++) { + for (row = i; row <= edge - i; ++row) { + matrix[i][row] = num++; + } + for (col = i + 1; col <= edge - i; ++col) { + matrix[col][edge - i] = num++; + } + if (edge - 2 * i >= 0) { + for (row = edge - i - 1; row >= i; --row) { + matrix[edge - i][row] = num++; + } + for (col = edge - i - 1; col > i; --col) { + matrix[col][i] = num++; + } + } + } + return matrix; + + } + + public static void main(String[] args) { + int n = 5; + int matrix[][] = new Q101_SpiralMatrix2().generateMatrixMy(n); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + //File + try { + FileWriter fw = new FileWriter("SpiralMatrix.html"); + fw.write(""); + for (int i = 0; i < n; i++) { + fw.write(""); + for (int j = 0; j < n; j++) { + fw.write(""); + } + fw.write(""); + } + fw.write("
" + matrix[i][j] + "
"); + fw.close(); + } catch (Exception ex) { + Logger.getLogger(Q101_SpiralMatrix2.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public int[][] generateMatrixMy(int n) { + int[][] matrix = new int[n][n]; + filloutMatrix(matrix, 0, n, 1); + return matrix; + } + + private void filloutMatrix(int[][] matrix, int n, int edge, int num) { + if (edge <= 0) { + return; + } + for (int i = 0; i < edge; i++) { + matrix[n][n + i] = num++; + } + for (int i = 1; i < edge; i++) { + matrix[n + i][n + edge - 1] = num++; + } + if (edge > 1) { + for (int i = 1; i < edge; i++) { + matrix[n + edge - 1][n + edge - 1 - i] = num++; + } + for (int i = 1; i < edge - 1; i++) { + matrix[n + edge - 1 - i][n] = num++; + } + } + filloutMatrix(matrix, n + 1, edge - 2, num); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q102_Sqrt.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q102_Sqrt.java new file mode 100644 index 0000000..545deb0 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q102_Sqrt.java @@ -0,0 +1,79 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q102_Sqrt { + + final double precis = 0.00001; + + public double sqrt(double x) { + double s = 0, e = x, m = x / 2; + while (s <= e) { + m = s + (e - s) / 2; + if (m * m > x) { + e = m - 1; + } else if (m * m < x) { + s = m + 1; + } else { + return m; + } + } + return m; + } + + public double sqrt2(double x) { + double m = x / 2, entropy = x / 2; + while (entropy > precis) { + if (m * m < x) { + m += entropy; + } else if (m * m > x) { + m -= entropy; + } else { + return m; + } + entropy /= 2; + } + return m; + } + + public double sqrtNewton(double n) { + double x = 1; + for (int i = 0; i < Integer.MAX_VALUE; i++) { + x = (x + n / 2) / 2; + } + return x; + } + + public static void main(String[] args) { + double val = 3; + double sqt = new Q102_Sqrt().sqrt2(val); + System.out.println(sqt); + + double binary = new Q102_Sqrt().sqrt(val); + System.out.println(binary); + + double my = new Q102_Sqrt().sqrtMy(val); + System.out.println(my); + + /* + double newton = new Q102_Sqrt().sqrtNewton(val); + System.out.println(newton); + */ + } + + public double sqrtMy(double x) { + double num = x / 2; + double dif = x / 4; + while (true) { + if (Math.abs(num * num - x) <= precis) { + return num; + } else if (num * num > x) { + num -= dif; + } else if (num * num < x) { + num += dif; + } + dif /= 2; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q103_StringToInteger.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q103_StringToInteger.java new file mode 100644 index 0000000..bd11526 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q103_StringToInteger.java @@ -0,0 +1,61 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q103_StringToInteger { + + public int atoi(String str) { + int i = 0, length = str.length(); + int val = 0; + boolean neg = false; + if (str.charAt(i) == '-') { + neg = true; + ++i; + } else if (str.charAt(i) == '+') { + ++i; + } + for (; i < length; ++i) { + if (str.charAt(i) < '0' || str.charAt(i) > '9') { + System.out.println("ERROR"); + return -1; + } + if ((Integer.MAX_VALUE - str.charAt(i)) / 10 < val) { + System.out.println("Overflow"); + return -1; + } + val *= 10; + val += str.charAt(i) - '0'; + } + if (neg) { + val *= -1; + } + return val; + } + + public static void main(String[] args) { + String str = "-1234567890"; + int num = new Q103_StringToInteger().atoiMy(str); + System.out.println(num); + } + + public int atoiMy(String str) { + int num = 0, len = str.length(), i = 0; + boolean neg = false; + if (str.charAt(0) == '+') { + ++i; + } else if (str.charAt(0) == '-') { + ++i; + neg = true; + } + for (; i < len; i++) { + int digit = str.charAt(i) - '0'; + num *= 10; + num += digit; + } + if (neg) { + num = -num; + } + return num; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q104_Subsets.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q104_Subsets.java new file mode 100644 index 0000000..d9f6a74 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q104_Subsets.java @@ -0,0 +1,11 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q104_Subsets { + + //the same as 105 + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q105_Subsets2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q105_Subsets2.java new file mode 100644 index 0000000..8e4ab37 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q105_Subsets2.java @@ -0,0 +1,40 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q105_Subsets2 { + + public static void main(String[] args) { + int[] num = {1, 2, 3}; + ArrayList> solution = new Q105_Subsets2().subsetsWithDupMy(num, num.length - 1); + for (ArrayList arrayList : solution) { + for (Integer integer : arrayList) { + System.out.print(integer + " "); + } + System.out.println(); + } + } + + public ArrayList> subsetsWithDupMy(int[] num, int last) { + if (last < 0) { + ArrayList> temp = new ArrayList<>(); + ArrayList temp_list = new ArrayList<>(); + temp.add(temp_list); + return temp; + } + ArrayList> solution = subsetsWithDupMy(num, last - 1); + int digit = num[last]; + ArrayList> more = new ArrayList<>(); + for (ArrayList list : solution) { + ArrayList temp = new ArrayList<>(); + temp.addAll(list); + temp.add(digit); + more.add(temp); + } + solution.addAll(more); + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q106_SubstringWithConcatenation.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q106_SubstringWithConcatenation.java new file mode 100644 index 0000000..0a1da01 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q106_SubstringWithConcatenation.java @@ -0,0 +1,123 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q106_SubstringWithConcatenation { + + public ArrayList findSubstring(String S, String[] L) { + ArrayList solution = new ArrayList<>(); + int i, j, l_size = L.length, step = L[0].length(), s_length = S.length(); + //filter duplicate + java.util.Arrays.sort(L); + ArrayList counts = new ArrayList<>(); + ArrayList entity = new ArrayList<>(); + for (i = 0; i < l_size; i++) { + entity.add(L[i]); + int count = 1; + while (i + 1 < l_size && L[i].equals(L[i + 1])) { + ++count; + } + counts.add(count); + } + // + int entity_size = entity.size(); + int starts[] = new int[s_length]; + for (i = 0; i < s_length; i++) { + String str = S.substring(i); + starts[i] = -1; + for (j = 0; j < entity_size; j++) { + if (str.startsWith(entity.get(j))) { + starts[i] = j; + } + } + } + // + for (i = 0; i <= s_length - step * l_size; i++) { + int perm[] = new int[l_size]; + boolean need_test = true; + for (j = 0; j < l_size; j++) { + perm[j] = starts[i + step * j]; + if (perm[j] == -1) { + need_test = false; + break; + } + } + if (need_test && testPerm(perm, counts)) { + solution.add(i); + } + } + return solution; + } + + private boolean testPerm(int perm[], ArrayList counts) { + int length = counts.size(), i; + int tab[] = new int[length]; + for (i = 0; i < perm.length; i++) { + ++tab[perm[i]]; + } + for (i = 0; i < length; i++) { + if (counts.get(i) != tab[i]) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + String L[] = {"bar", "foo"}; + String S = "barbarxxxfoobar"; + ArrayList solution = new Q106_SubstringWithConcatenation().findSubstringMy(S, L); + for (Integer integer : solution) { + System.out.println(integer); + } + } + + public ArrayList findSubstringMy(String S, String[] L) { + ArrayList solution = new ArrayList<>(); + int s_len = S.length(), l_len = L.length; + int[] pos = new int[s_len]; + for (int i = 0; i < s_len; i++) { + pos[i] = -1; + } + for (int i = 0; i < s_len; i++) { + for (int g = 0; g < l_len; g++) { + if (S.startsWith(L[g], i)) { + pos[i] = g; + break; + } + } + } + for (int i = 0; i < s_len; i++) { + if (pos[i] != -1) { + boolean[] find = new boolean[l_len]; + if (match(pos, find, i, L[0].length())) { + solution.add(i); + } + } + } + return solution; + } + + boolean match(int[] pos, boolean[] find, int i, int len) { + int match = 0; + for (int j = i; j < pos.length; j += len) { + int p = pos[j]; + if (p != - 1) { + if (find[p]) { + return false; + } else { + ++match; + find[p] = true; + } + } + } + if (match == find.length) { + return true; + } else { + return false; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q107_SudokuSolver.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q107_SudokuSolver.java new file mode 100644 index 0000000..82d8c92 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q107_SudokuSolver.java @@ -0,0 +1,88 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q107_SudokuSolver { + + public boolean solveSudoku(char[][] board) { + int height = board.length, width = board[0].length, col, row; + for (col = 0; col < height; ++col) { + for (row = 0; row < width; row++) { + if (board[col][row] == '.') { + for (char ch = '1'; ch <= '9'; ch++) { + board[col][row] = ch; + if (isValid(board, col, row)) { + if (solveSudoku(board)) { + return true; + } + } + board[col][row] = '.'; + } + return false; + } + } + } + return true; + } + + private boolean isValid(char[][] board, int col, int row) { + int i, j; + boolean tab[] = new boolean[9]; + for (i = 0; i < 9; i++) { + if (board[col][i] != '.') { + if (tab[board[col][i] - '1']) { + return false; + } else { + tab[board[col][i] - '1'] = true; + } + } + } + tab = new boolean[9]; + for (i = 0; i < 9; i++) { + if (board[i][row] != '.') { + if (tab[board[i][row] - '1']) { + return false; + } else { + tab[board[i][row] - '1'] = true; + } + } + } + tab = new boolean[9]; + for (i = (col / 3) * 3; i < (col / 3) * 3 + 3; i++) { + for (j = (row / 3) * 3; j < (row / 3) * 3 + 3; j++) { + if (board[i][j] != '.') { + if (tab[board[i][j] - '1']) { + return false; + } else { + tab[board[i][j] - '1'] = true; + } + } + } + } + return true; + } + + public static void main(String[] args) { + char[][] board = { + {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'} + }; + boolean result = new Q107_SudokuSolver().solveSudoku(board); + + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + System.out.print(board[i][j] + " "); + } + System.out.println(); + } + System.out.println(result); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q108_SwapNodesInPairs.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q108_SwapNodesInPairs.java new file mode 100644 index 0000000..2d2ac65 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q108_SwapNodesInPairs.java @@ -0,0 +1,109 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q108_SwapNodesInPairs { + + public LinkedListNode swapPairs(LinkedListNode head) { + LinkedListNode FakeHead = new LinkedListNode<>(0); + FakeHead.Next = head; + LinkedListNode l1 = head, l2 = head, pre = FakeHead, cur = head, NewHead = head.Next; + while (cur != null && cur.Next != null) { + l1 = cur; + l2 = cur.Next; + cur = cur.Next.Next; + l2.Next = l1; + l1.Next = cur; + pre.Next = l2; + pre = l1; + } + return NewHead; + } + + public LinkedListNode swapPairsEx(LinkedListNode head) { + LinkedListNode cur = head, pre = null, next = head.Next, NewHead = head.Next, LastEnd = null; + int count = 1; + while (cur != null) { + if (count++ % 2 == 0) { + cur.Next = pre; + LastEnd = pre; + } else { + if (LastEnd != null) { + LastEnd.Next = next; + } + } + pre = cur; + cur = next; + if (next != null) { + next = next.Next; + } + } + if (count % 2 == 1) { + LastEnd.Next = null; + } else { + LastEnd.Next = pre; + } + return NewHead; + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList(); + head.print(); + System.out.println("-=-=-=-=-=-=-"); + LinkedListNode NewHead = new Q108_SwapNodesInPairs().swapPairsMy(head); + NewHead.print(); + } + + public LinkedListNode swapPairsSample(LinkedListNode head) { + LinkedListNode sent = new LinkedListNode(0); + sent.Next = head; + + if (head == null) { + return null; + } + LinkedListNode cur = head, pre = sent, next = head.Next; + while (next != null) { + cur.Next = next.Next; + next.Next = cur; + pre.Next = next; + + pre = next; + next = cur.Next; + if (next != null) { + pre = cur; + cur = next; + next = next.Next; + } + } + + + return sent.Next; + } + + public LinkedListNode swapPairsMy(LinkedListNode head) { + LinkedListNode sent = new LinkedListNode(0); + sent.Next = head; + + if (head == null) { + return null; + } + LinkedListNode pre = sent, cur = head, next = head.Next; + while (next != null) { + cur.Next = next.Next; + next.Next = cur; + pre.Next = next; + + pre = cur; + cur = cur.Next; + if (cur != null) { + next = cur.Next; + } else { + break; + } + } + return sent.Next; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q109_SymmetricTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q109_SymmetricTree.java new file mode 100644 index 0000000..2359aca --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q109_SymmetricTree.java @@ -0,0 +1,41 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q109_SymmetricTree { + + public boolean isSymmetric(BinaryTreeNode root) { + if (root.Left == null && root.Right == null) { + return true; + } else if (root.Left != null && root.Right != null) { + return root.Left.Data == root.Right.Data && isSymmetric(root.Left) && isSymmetric(root.Right); + } else { + return false; + } + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + boolean result = new Q109_SymmetricTree().isSymmetricMy(root, root); + System.out.println(result); + BinaryTreeNode root2 = BinaryTreeNode.getSampleTree2(); + boolean result2 = new Q109_SymmetricTree().isSymmetricMy(root2, root2); + System.out.println(result2); + } + + //most correct one + public boolean isSymmetricMy(BinaryTreeNode root, BinaryTreeNode root2) { + if (root == null && root2 == null) { + return true; + } else if ((root == null && root2 != null) || (root != null && root2 == null)) { + return false; + } else if (root.Data != root2.Data) { + return false; + } else { + return isSymmetricMy(root.Left, root2.Right) && isSymmetricMy(root.Right, root2.Left); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q10_BestTimeBuySellStock3.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q10_BestTimeBuySellStock3.java new file mode 100644 index 0000000..0828824 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q10_BestTimeBuySellStock3.java @@ -0,0 +1,74 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q10_BestTimeBuySellStock3 { + + //wrong + public int maxProfit(int[] prices) { + int i = 1, length = prices.length, MaxProfitVal = Integer.MIN_VALUE; + int[] left = new int[length]; + int[] right = new int[length]; + int buy_day = 0; + for (i = 1; i < length; ++i) { + left[i] = prices[i] - prices[buy_day]; + buy_day = prices[i] < prices[buy_day] ? i : buy_day; + } + int sell_day = length - 1; + for (i = length - 2; i >= 0; --i) { + right[i] = prices[sell_day] - prices[i]; + sell_day = prices[i] > prices[sell_day] ? i : sell_day; + } + for (i = 1; i < length; i++) { + int current_profit = left[i - 1] + right[i]; + if (current_profit > MaxProfitVal) { + MaxProfitVal = current_profit; + } + } + return MaxProfitVal; + } + + //my way + public int maxProfitEx(int[] prices) { + int max = Integer.MIN_VALUE; + int length = prices.length, i; + int[] left = new int[length]; + int sell_date = 0; + int buy_date = 0; + for (i = 1; i < length; i++) { + if (prices[i] < prices[buy_date]) { + buy_date = i; + } + if (prices[sell_date] < prices[i] && i > buy_date) { + sell_date = i; + } + left[i] = prices[sell_date] - prices[buy_date]; + } + int[] right = new int[length]; + sell_date = length - 1; + buy_date = length - 1; + for (i = length - 2; i >= 0; i--) { + if (prices[i] > prices[sell_date]) { + sell_date = i; + } + if (prices[buy_date] > prices[i] && i < sell_date) { + buy_date = i; + } + right[i] = prices[sell_date] - prices[buy_date]; + + } + for (i = 1; i < length; i++) { + max = Math.max(max, left[i - 1] + right[i]); + } + return max; + } + + public static void main(String[] args) { + int[] prices = {2, 3, 1, 100, 7, 2, 9, 10}; + int profit = new Q10_BestTimeBuySellStock3().maxProfit(prices); + System.out.println(profit); + int profit2 = new Q10_BestTimeBuySellStock3().maxProfitEx(prices); + System.out.println(profit2); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q110_TextJustification.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q110_TextJustification.java new file mode 100644 index 0000000..2b5ff7e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q110_TextJustification.java @@ -0,0 +1,113 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import com.sun.org.apache.xml.internal.serializer.ToTextSAXHandler; +import java.util.ArrayList; +import sun.reflect.generics.tree.IntSignature; + +public class Q110_TextJustification { + + public ArrayList fullJustify(String[] words, int L) { + ArrayList solution = new ArrayList<>(); + int i, length = words.length; + int char_count = 0, s = 0; + for (i = 0; i < length; i++) { + char_count += words[i].length(); + if (char_count + (i - s) > L) { + char_count -= 1 + words[i].length(); + solution.add(fullJustifyHelper(words, s, i - 1, L)); + char_count = 0; + s = i; + } + if (i == length - 1) { + solution.add(fullJustifyHelper(words, s, i, L)); + } + } + return solution; + } + + private String fullJustifyHelper(String[] words, int s, int e, int L) { + for (int i = s; i <= e; i++) { + L -= words[i].length(); + } + int space = L, space_offset = 0; + if (e > s) { + space = L / (e - s); + space_offset = L % (e - s); + } + StringBuilder sb = new StringBuilder(); + for (int i = s; i <= e; i++) { + sb.append(words[i]); + int size = space; + if (i == s) { + size += space_offset; + } else if (i == e) { + break; + } + for (int j = 0; j < size; j++) { + sb.append("_"); + } + } + return sb.toString(); + } + + public static void main(String[] args) { + String words[] = {"This", "is", "an", "example", "of", "text", "justification."}; + int L = 16; + ArrayList solution = new Q110_TextJustification().fullJustifyMy(words, L); + for (String string : solution) { + System.out.println(string); + } + } + + public ArrayList fullJustifyMy(String[] words, int L) { + ArrayList solution = new ArrayList<>(); + int s = 0, count = words[0].length(); + for (int i = 1; i < words.length; i++) { + count += 1 + words[i].length(); + if (count > L) { + String temp = generateLine(words, s, i - 1, L); + s = i; + count = 0; + solution.add(temp); + } + } + if (s <= words.length - 1) { + String temp = generateLine(words, s, words.length - 1, L); + solution.add(temp); + } + return solution; + } + + String generateLine(String[] words, int s, int e, int L) { + StringBuilder sb = new StringBuilder(); + int word_num = e - s + 1, total_empty = L; + if (word_num > 1) { + for (int i = s; i <= e; i++) { + total_empty -= words[i].length(); + } + int per_empty = total_empty / (word_num - 1); + int per_empty_offset = total_empty % (word_num - 1); + for (int i = s; i <= e; i++) { + sb.append(words[i]); + if (i == s) { + for (int count = 0; count < per_empty + per_empty_offset; count++) { + sb.append("_"); + } + } else if (i <= e - 1) { + for (int count = 0; count < per_empty; count++) { + sb.append("_"); + } + } + } + } else if (word_num == 1) { + sb.append(words[s]); + for (int count = 0; count < L - words[s].length(); count++) { + sb.append("_"); + } + } + return sb.toString(); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q111_TrappingRainWater.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q111_TrappingRainWater.java new file mode 100644 index 0000000..2bafe66 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q111_TrappingRainWater.java @@ -0,0 +1,68 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q111_TrappingRainWater { + + public int trap(int[] A) { + int h_val = A[0], h = 0, length = A.length, i; + for (i = 1; i < length; i++) { + if (A[i] > h_val) { + h_val = A[i]; + h = i; + } + } + int water = 0; + int p = A[0]; + for (i = 1; i < h; ++i) { + if (A[i] < p) { + water += p - A[i]; + } else { + p = A[i]; + } + } + p = A[length - 1]; + for (i = length - 2; i > h; --i) { + if (A[i] < p) { + water += p - A[i]; + } else { + p = A[i]; + } + } + return water; + } + + public static void main(String[] args) { + int[] A = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + int water = new Q111_TrappingRainWater().trapMy(A); + System.out.println(water); + } + + public int trapMy(int[] A) { + int water = 0, len = A.length, h = A[0], hi = 0; + for (int i = 1; i < len; i++) { + if (A[i] > h) { + h = A[i]; + hi = i; + } + } + int p = A[0]; + for (int i = 1; i < hi; i++) { + if (A[i] > p) { + p = A[i]; + } else { + water += p - A[i]; + } + } + p = A[len - 1]; + for (int i = len - 2; i > hi; i--) { + if (A[i] > p) { + p = A[i]; + } else { + water += p - A[i]; + } + } + return water; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q112_Triangle.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q112_Triangle.java new file mode 100644 index 0000000..891aaac --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q112_Triangle.java @@ -0,0 +1,119 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.HashMap; + +public class Q112_Triangle { + + public int minimumTotal(ArrayList> triangle) { + cache = new HashMap<>(); + int count = minimumTotalHelper(0, 0, triangle, triangle.size() - 1); + return count; + } + private HashMap cache; + + private int minimumTotalHelper(int pos, int level, ArrayList> triangle, int end) { + if (level > end) { + return 0; + } + String key = String.valueOf(level) + "-" + String.valueOf(pos); + if (cache.containsKey(key)) { + return cache.get(key); + } + if (minimumTotalHelper(pos, level + 1, triangle, end) >= minimumTotalHelper(pos + 1, level + 1, triangle, end)) { + int cur = triangle.get(level).get(pos) + minimumTotalHelper(pos + 1, level + 1, triangle, end); + cache.put(key, cur); + return cur; + } else { + int cur = triangle.get(level).get(pos) + minimumTotalHelper(pos, level + 1, triangle, end); + cache.put(key, cur); + return cur; + } + } + + public static void main(String[] args) { + ArrayList> triangle = new ArrayList<>(); + ArrayList level1 = new ArrayList<>(); + level1.add(2); + ArrayList level2 = new ArrayList<>(); + level2.add(3); + level2.add(4); + ArrayList level3 = new ArrayList<>(); + level3.add(6); + level3.add(5); + level3.add(7); + ArrayList level4 = new ArrayList<>(); + level4.add(4); + level4.add(1); + level4.add(8); + level4.add(3); + triangle.add(level1); + triangle.add(level2); + triangle.add(level3); + triangle.add(level4); + int count = new Q112_Triangle().minimumTotalMyDP(triangle); + System.out.println(count); + + } + + public int minimumTotalMy(ArrayList> triangle) { + my_cache = new HashMap<>(); + return getMinimum(0, 0, triangle); + } + HashMap my_cache = null; + + int getMinimum(int level, int i, ArrayList> triangle) { + if (level == triangle.size()) { + return 0; + } + String key = String.valueOf(level) + "|" + String.valueOf(i); + if (my_cache.containsKey(key)) { + return my_cache.get(key); + } + if (getMinimum(level + 1, i, triangle) <= getMinimum(level + 1, i + 1, triangle)) { + int count = getMinimum(level + 1, i, triangle) + triangle.get(level).get(i); + my_cache.put(key, count); + return count; + } else { + int count = getMinimum(level + 1, i + 1, triangle) + triangle.get(level).get(i); + my_cache.put(key, count); + return count; + } + } + + public int minimumTotalMyDP(ArrayList> triangle) { + ArrayList> DP = new ArrayList<>(); + for (int level = 0; level < triangle.size(); level++) { + ArrayList temp = new ArrayList<>(); + for (int row = 0; row < triangle.get(level).size(); row++) { + if (level == 0) { + temp.add(triangle.get(level).get(0)); + } else { + if (row == 0) { + temp.add(DP.get(level - 1).get(row) + triangle.get(level).get(row)); + } else if (row == triangle.get(level).size() - 1) { + temp.add(DP.get(level - 1).get(row - 1) + triangle.get(level).get(row)); + } else { + if (DP.get(level - 1).get(row) <= DP.get(level - 1).get(row - 1)) { + temp.add(DP.get(level - 1).get(row) + triangle.get(level).get(row)); + } else { + temp.add(DP.get(level - 1).get(row - 1) + triangle.get(level).get(row)); + } + } + } + } + DP.add(temp); + } + ArrayList last_layer = DP.get(DP.size() - 1); + int min = Integer.MAX_VALUE; + for (Integer integer : last_layer) { + if (integer < min) { + min = integer; + } + } + return min; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q113_TwoSum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q113_TwoSum.java new file mode 100644 index 0000000..a83d487 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q113_TwoSum.java @@ -0,0 +1,95 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.HashMap; + +public class Q113_TwoSum { + + public ArrayList twoSum(int[] numbers, int target) { + ArrayList solution = new ArrayList<>(); + int s = 0, length = numbers.length, e = length - 1, i; + HashMap pos = new HashMap<>(); + for (i = 0; i < length; i++) { + if (!pos.containsKey(numbers[i])) { + pos.put(numbers[i], i + 1); + } else if (numbers[i] * 2 == target) { + solution.add(pos.get(numbers[i])); + solution.add(i + 1); + } + } + java.util.Arrays.sort(numbers); + while (s < e) { + if (numbers[s] + numbers[e] < target) { + ++s; + } else if (numbers[s] + numbers[e] > target) { + --e; + } else { + solution.add(pos.get(numbers[s])); + solution.add(pos.get(numbers[e])); + ++s; + --e; + /*boolean ss = true, ee = true; + while (s + 1 < e && numbers[s] == numbers[s + 1]) { + ss = false; + ++s; + solution.add(pos.get(numbers[s])); + solution.add(pos.get(numbers[e])); + } + while (e - 1 > s && numbers[e] == numbers[e - 1]) { + ee = false; + --e; + solution.add(pos.get(numbers[s])); + solution.add(pos.get(numbers[e])); + } + if (ss) { + ++s; + } + if (ee) { + --e; + }*/ + } + } + return solution; + } + + public static void main(String[] args) { + int[] numbers = {1, 1, 9, 2, 8, 5, 5, 5, 0, 11, 12, 6}; + int target = 10; + ArrayList solution = new Q113_TwoSum().twoSumMy(numbers, target); + for (int i = 0; i < solution.size() - 1; i += 2) { + System.out.println(solution.get(i) + "-" + solution.get(1 + i)); + } + } + + public ArrayList twoSumMy(int[] numbers, int target) { + ArrayList solution = new ArrayList<>(); + HashMap pos = new HashMap<>(); + for (int i = 0; i < numbers.length; i++) { + if (!pos.containsKey(numbers[i])) { + pos.put(numbers[i], i + 1); + } else if (numbers[i] * 2 == target) { + solution.add(pos.get(numbers[i])); + solution.add(i + 1); + } + } + java.util.Arrays.sort(numbers); + int s = 0, e = numbers.length - 1; + while (s < e) { + int sum = numbers[s]+numbers[e]; + if (sum == target) { + solution.add(pos.get(numbers[s])); + solution.add(pos.get(numbers[e])); + ++s; + --e; + } else if (sum > target) { + --e; + } else { + ++s; + } + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q114_UniqueBinarySearchTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q114_UniqueBinarySearchTree.java new file mode 100644 index 0000000..07f2893 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q114_UniqueBinarySearchTree.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q114_UniqueBinarySearchTree { + + public int numTrees(int n) { + return numTreesHelper(1, n); + } + + private int numTreesHelper(int s, int e) { + if (s >= e) { + return 1; + } + int ways = 0, left = 0, right = 0; + for (int i = s; i <= e; i++) { + left = numTreesHelper(s, i - 1); + right = numTreesHelper(i + 1, e); + ways += left * right; + } + return ways; + } + + public static void main(String[] args) { + int n = 3; + int ways = new Q114_UniqueBinarySearchTree().numTreesMy(n); + System.out.println(ways); + } + + public int numTreesMy(int n) { + return numTreeHelper(1, n); + } + + int numTreeHelper(int s, int e) { + if (s > e) { + return 1; + } + int ways = 0, l = 0, r = 0; + for (int i = s; i <= e; i++) { + l = numTreeHelper(s, i - 1); + r = numTreeHelper(i + 1, e); + ways += l * r; + } + return ways; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q115_UniqueBinarySearchTree2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q115_UniqueBinarySearchTree2.java new file mode 100644 index 0000000..55287bb --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q115_UniqueBinarySearchTree2.java @@ -0,0 +1,66 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; + +public class Q115_UniqueBinarySearchTree2 { + + public ArrayList> generateTrees(int n) { + return generateTreesHelper(1, n); + } + + private ArrayList> generateTreesHelper(int s, int e) { + ArrayList> solution = new ArrayList<>(); + if (s > e) { + solution.add(null); + return solution; + } + for (int i = s; i <= e; i++) { + ArrayList> Lefts = generateTreesHelper(s, i - 1); + ArrayList> Rights = generateTreesHelper(i + 1, e); + for (BinaryTreeNode LeftNode : Lefts) { + for (BinaryTreeNode RightNode : Rights) { + BinaryTreeNode root = new BinaryTreeNode<>(i); + root.Left = LeftNode; + root.Right = RightNode; + solution.add(root); + } + } + } + return solution; + } + + public static void main(String[] args) { + int n = 3; + ArrayList> solution = new Q115_UniqueBinarySearchTree2().generateTreesMy(n); + System.out.println(solution.size()); + } + + public ArrayList> generateTreesMy(int n) { + return getRootMyHelper(1, n); + } + + ArrayList> getRootMyHelper(int s, int e) { + ArrayList> solution = new ArrayList<>(); + if (s > e) { + solution.add(null); + return solution; + } + for (int i = s; i <= e; i++) { + ArrayList> l = getRootMyHelper(s, i - 1); + ArrayList> r = getRootMyHelper(i + 1, e); + for (BinaryTreeNode l_node : l) { + for (BinaryTreeNode r_node : r) { + BinaryTreeNode btn = new BinaryTreeNode<>(i); + btn.Left = l_node; + btn.Right = r_node; + solution.add(btn); + } + } + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q116_UniquePath.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q116_UniquePath.java new file mode 100644 index 0000000..f199b0b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q116_UniquePath.java @@ -0,0 +1,87 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.HashMap; + +public class Q116_UniquePath { + + public int uniquePathsDP(int m, int n) { + int[][] DP = new int[m][n]; + int i, j; + DP[0][0] = 1; + for (i = 1; i < m; i++) { + DP[i][0] = 1; + } + for (i = 1; i < n; i++) { + DP[0][i] = 1; + } + for (i = 1; i < m; i++) { + for (j = 1; j < n; j++) { + DP[i][j] = DP[i - 1][j] + DP[i][j - 1]; + } + } + return DP[m - 1][n - 1]; + } + + public int uniquePaths(int m, int n) { + cache = new HashMap<>(); + return uniquePathsHelper(m, n); + } + HashMap cache; + + private int uniquePathsHelper(int m, int n) { + if (m == 1 && n == 1) { + return 1; + } + String key = String.valueOf(m) + "-" + String.valueOf(n); + if (cache.containsKey(key)) { + return cache.get(key); + } + int ways = 0; + if (m > 0) { + ways += uniquePathsHelper(m - 1, n); + } + if (n > 0) { + ways += uniquePathsHelper(m, n - 1); + } + cache.put(key, ways); + return ways; + } + + public static void main(String[] args) { + int m = 1, n = 1; + int ways = new Q116_UniquePath().uniquePathsMy(m, n); + System.out.println(ways); + int ways2 = new Q116_UniquePath().uniquePathsDP(m, n); + System.out.println(ways2); + + int tm = 100, tn = 100; + long l1 = System.currentTimeMillis(); + int tways = new Q116_UniquePath().uniquePathsMy(tm, tn); + long l2 = System.currentTimeMillis(); + int tways2 = new Q116_UniquePath().uniquePathsDP(tm, tn); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(tways + " Cost " + span1); + System.out.println(tways2 + " Cost " + span2); + } + + public int uniquePathsMy(int m, int n) { + int[][] matrix = new int[m][n]; + matrix[0][0] = 1; + for (int i = 1; i < m; i++) { + matrix[i][0] = 1; + } + for (int i = 1; i < n; i++) { + matrix[0][i] = 1; + } + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1]; + } + } + return matrix[m - 1][n - 1]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q117_UniquePath2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q117_UniquePath2.java new file mode 100644 index 0000000..9e6d3d2 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q117_UniquePath2.java @@ -0,0 +1,38 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q117_UniquePath2 { + + //the same as Q116 + public static void main(String[] args) { + } + + public int uniquePathsMy(int m, int n) { + int[][] matrix = new int[m][n]; + matrix[0][0] = 1; + for (int i = 1; i < m; i++) { + if (isFree(i, 0)) { + matrix[i][0] = 1; + } + } + for (int i = 1; i < n; i++) { + if (isFree(0, i)) { + matrix[0][i] = 1; + } + } + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (isFree(i, j)) { + matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1]; + } + } + } + return matrix[m - 1][n - 1]; + } + + boolean isFree(int m, int n) { + return true; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q118_ValidNumber.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q118_ValidNumber.java new file mode 100644 index 0000000..b690ae4 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q118_ValidNumber.java @@ -0,0 +1,43 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q118_ValidNumber { + + public static void main(String[] args) { + Q118_ValidNumber q118 = new Q118_ValidNumber(); + String s = "12.3"; + System.out.println(q118.isNum(s)); + } + + boolean isNum(String s) { + boolean e = false, dot = false; + if (s.charAt(0) == 'e') { + return false; + } + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == 'e') { + if (e) { + return false; + } else { + e = true; + } + } else if (s.charAt(i) == '.') { + if (dot) { + return false; + } else { + dot = true; + } + } else if (!isNum(s.charAt(i))) { + return false; + } + } + + return true; + } + + boolean isNum(char c) { + return c >= '0' && c <= '9'; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q119_ValidParentheses.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q119_ValidParentheses.java new file mode 100644 index 0000000..332bf6a --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q119_ValidParentheses.java @@ -0,0 +1,12 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q119_ValidParentheses { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q11_BinaryTreeInOrderTraversal.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q11_BinaryTreeInOrderTraversal.java new file mode 100644 index 0000000..df5377b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q11_BinaryTreeInOrderTraversal.java @@ -0,0 +1,62 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; +import java.util.Stack; + +public class Q11_BinaryTreeInOrderTraversal { + + public ArrayList inorderTraversal(BinaryTreeNode root) { + ArrayList solution = new ArrayList<>(); + BinaryTreeNode runner = root; + Stack> s = new Stack<>(); + s.add(runner); + runner = runner.Left; + while (!s.isEmpty() || runner != null) { + while (runner != null) { + s.add(runner); + runner = runner.Left; + } + if (!s.isEmpty()) { + runner = s.pop(); + } + if (runner != null) { + solution.add(runner.Data); + } + runner = runner.Right; + } + return solution; + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + Q11_BinaryTreeInOrderTraversal q11 = new Q11_BinaryTreeInOrderTraversal(); + ArrayList solution = q11.inorderTraversalMy(root); + for (Integer integer : solution) { + System.out.println(integer); + } + } + + public ArrayList inorderTraversalMy(BinaryTreeNode root) { + ArrayList solution = new ArrayList<>(); + BinaryTreeNode runner = root; + Stack> stack = new Stack<>(); + while (!stack.isEmpty() || runner != null) { + while (runner != null) { + stack.push(runner); + runner = runner.Left; + } + if (!stack.isEmpty()) { + runner = stack.pop(); + solution.add(runner.Data); + } + if (runner != null) { + runner = runner.Right; + } + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q120_ValidSudoku.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q120_ValidSudoku.java new file mode 100644 index 0000000..c0bb2b0 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q120_ValidSudoku.java @@ -0,0 +1,13 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q120_ValidSudoku { + + //reference tp Q107 + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q121_ValidBinarySearchTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q121_ValidBinarySearchTree.java new file mode 100644 index 0000000..545dc86 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q121_ValidBinarySearchTree.java @@ -0,0 +1,12 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q121_ValidBinarySearchTree { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q122_WildcardMatching.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q122_WildcardMatching.java new file mode 100644 index 0000000..7f38330 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q122_WildcardMatching.java @@ -0,0 +1,72 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q122_WildcardMatching { + + public boolean isMatch(String s, String p) { + int s_length = s.length(), p_length = p.length(); + if (s_length == 0) { + return p_length == 0 || allStar(p); + } else if (p_length == 0) { + return s_length == 0; + } else if (p.charAt(0) == s.charAt(0) || p.charAt(0) == '?') { + return isMatch(s.substring(1), p.substring(1)); + } else if (p.charAt(0) == '*') { + return isMatch(s.substring(1), p) || isMatch(s, p.substring(1)); + } else { + return false; + } + } + + private boolean allStar(String p) { + for (int i = 0; i < p.length(); i++) { + if (p.charAt(i) != '*') { + return false; + } + } + return true; + } + + public static void main(String[] args) { + String s = "zhaosanqiang"; + String p = "zhao?an*g"; + boolean match = new Q122_WildcardMatching().isMatch(s, p); + System.out.println(match); + boolean match2 = new Q122_WildcardMatching().isMatchMy(s, p); + System.out.println(match2); + } + + public boolean isMatchMy(String s, String p) { + int s_len = s.length(), p_len = p.length(); + if (s.equals(p)) { + return true; + } else if (s_len == 0 && p_len != 0) { + if (allStarMy(p)) { + return true; + } else { + return false; + } + } else if (s_len != 0 && p_len == 0) { + return false; + } else if (p.charAt(0) == '?') { + return isMatch(s.substring(1), p.substring(1)); + } else if (p.charAt(0) == '*') { + return isMatch(s.substring(1), p) || isMatchMy(s, p.substring(1)); + } else if (s.charAt(0) == p.charAt(0)) { + return isMatch(s.substring(1), p.substring(1)); + } else { + return false; + } + } + + private boolean allStarMy(String p) { + for (char ch : p.toCharArray()) { + if (ch != '*') { + return false; + } + } + return true; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q123_WordSearch.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q123_WordSearch.java new file mode 100644 index 0000000..e50957f --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q123_WordSearch.java @@ -0,0 +1,110 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q123_WordSearch { + + public boolean exist(char[][] board, String word) { + int height = board.length, width = board[0].length; + boolean record[][] = new boolean[height][width]; + for (int col = 0; col < height; col++) { + for (int row = 0; row < width; row++) { + if (board[col][row] == word.charAt(0)) { + if (existHelper(board, record, col, row, word, 0)) { + return true; + } + } + } + } + return false; + } + + private boolean existHelper(char[][] board, boolean[][] record, int col, int row, String word, int index) { + if (index == word.length() - 1) { + return true; + } + record[col][row] = true; + char ch = word.charAt(index + 1); + int height = board.length, width = board[0].length; + boolean up = false; + if (col - 1 >= 0 && ch == board[col - 1][row] && !record[col - 1][row]) { + up = existHelper(board, record, col - 1, row, word, index + 1); + record[col - 1][row] = false; + } + if (up) { + return true; + } + boolean down = false; + if (col + 1 < height && ch == board[col + 1][row] && !record[col + 1][row]) { + down = existHelper(board, record, col + 1, row, word, index + 1); + record[col + 1][row] = false; + } + if (down) { + return true; + } + boolean left = false; + if (row - 1 >= 0 && ch == board[col][row - 1] && !record[col][row - 1]) { + up = existHelper(board, record, col, row - 1, word, index + 1); + record[col][row - 1] = false; + } + if (left) { + return true; + } + boolean right = false; + if (row + 1 < width && ch == board[col][row + 1] && !record[col][row + 1]) { + up = existHelper(board, record, col, row + 1, word, index + 1); + record[col][row + 1] = false; + } + if (right) { + return true; + } + return left | right | up | down; + } + + public static void main(String[] args) { + char[][] board = { + {'A', 'B', 'C', 'E'}, + {'S', 'F', 'C', 'S'}, + {'A', 'D', 'E', 'E'} + }; + String word = "ABCCE"; + boolean result = new Q123_WordSearch().existMy(board, word); + System.out.println(result); + } + + public boolean existMy(char[][] board, String word) { + if (word.length() == 0) { + return true; + } + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if (board[i][j] == word.charAt(0) && go(board, word, 1, i, j)) { + return true; + } + } + } + return false; + } + + boolean go(char[][] board, String word, int i, int col, int row) { + if (word.length() == i) { + return true; + } else if (col < 0 || col >= board.length || row < 0 || row >= board[0].length) { + return false; + } + if (col + 1 < board.length && board[col + 1][row] == word.charAt(i) && go(board, word, i + 1, col + 1, row)) { + return true; + } + if (col - 1 >= 0 && board[col - 1][row] == word.charAt(i) && go(board, word, i + 1, col - 1, row)) { + return true; + } + if (row + 1 < board[0].length && board[col][row + 1] == word.charAt(i) && go(board, word, i + 1, col, row + 1)) { + return true; + } + if (row - 1 >= 0 && board[col][row - 1] == word.charAt(i) && go(board, word, i + 1, col, row - 1)) { + return true; + } + return false; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q124_ZigzagConversion.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q124_ZigzagConversion.java new file mode 100644 index 0000000..f8e25ca --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q124_ZigzagConversion.java @@ -0,0 +1,71 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 26, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q124_ZigzagConversion { + + public String convert(String s, int nRows) { + StringBuilder sb = new StringBuilder(); + int s_length = s.length(), section_per_num = nRows * 2 - 2, k, + section_size = s_length % section_per_num == 0 ? s_length / section_per_num : s_length / section_per_num + 1; + for (int r = 0; r < nRows; ++r) { + for (int sec = 0; sec < section_size; sec++) { + if (r == 0) { + k = sec * section_per_num + r; + if (k < s_length) { + sb.append(s.charAt(k)); + } + } else if (r == nRows - 1) { + k = sec * section_per_num + r; + if (k < s_length) { + sb.append(s.charAt(k)); + } + } else { + k = sec * section_per_num + r; + if (k < s_length) { + sb.append(s.charAt(k)); + } + k = sec * section_per_num + r + nRows / 2 + 1; + if (k < s_length) { + sb.append(s.charAt(k)); + } + } + } + } + return sb.toString(); + } + + public static void main(String[] args) { + String s = "ABCDEFGHIJKLO"; + int nRows = 3; + String rotate = new Q124_ZigzagConversion().convertMy(s, nRows); + System.out.println(rotate); + String rotate2 = new Q124_ZigzagConversion().convert(s, nRows); + System.out.println(rotate2); + } + + public String convertMy(String s, int nRows) { + StringBuilder sb = new StringBuilder(); + int sector = nRows * 2 - 2, len = s.length(), num_sector = len % sector == 0 ? len / sector : 1 + len / sector; + for (int pos = 0; pos < nRows; pos++) { + for (int si = 0; si < num_sector; si++) { + int cur = si * sector + pos; + if (cur >= len) { + continue; + } + if (pos == 0 || pos == nRows - 1) { + sb.append(s.charAt(cur)); + } else { + sb.append(s.charAt(cur)); + if (cur + nRows/2+1 >= len) { + continue; + } else { + sb.append(s.charAt(cur + nRows / 2 + 1)); + } + } + } + } + return sb.toString(); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q12_BinaryTreeLevelOrderTraversal.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q12_BinaryTreeLevelOrderTraversal.java new file mode 100644 index 0000000..f201d89 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q12_BinaryTreeLevelOrderTraversal.java @@ -0,0 +1,44 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; + +public class Q12_BinaryTreeLevelOrderTraversal { + + public ArrayList> levelOrder(BinaryTreeNode root) { + ArrayList> solutions = new ArrayList<>(); + levelOrderHelper(solutions, 0, root); + return solutions; + } + + private void levelOrderHelper(ArrayList> solutions, int level, BinaryTreeNode head) { + if (head == null) { + return; + } + ArrayList list = null; + if (solutions.size() - 1 < level) { + list = new ArrayList<>(); + solutions.add(list); + } else { + list = solutions.get(level); + } + list.add(head.Data); + levelOrderHelper(solutions, level + 1, head.Left); + levelOrderHelper(solutions, level + 1, head.Right); + } + + public static void main(String[] args) { + Q12_BinaryTreeLevelOrderTraversal q12 = new Q12_BinaryTreeLevelOrderTraversal(); + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + ArrayList> solutions = q12.levelOrder(root); + for (ArrayList arrayList : solutions) { + for (Integer integer : arrayList) { + System.out.print(integer+","); + } + System.out.println(); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q13_BinaryTreeLevelOrderTraversal2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q13_BinaryTreeLevelOrderTraversal2.java new file mode 100644 index 0000000..7365839 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q13_BinaryTreeLevelOrderTraversal2.java @@ -0,0 +1,42 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; + +public class Q13_BinaryTreeLevelOrderTraversal2 { + + public ArrayList> levelOrderBottom(BinaryTreeNode root) { + ArrayList> solutions = new ArrayList<>(); + int height = root.getHeight(); + for (int i = 0; i < height; i++) { + solutions.add(new ArrayList()); + } + levelOrderHelper(solutions, 0, height, root); + return solutions; + } + + private void levelOrderHelper(ArrayList> solutions, int level, int height, BinaryTreeNode head) { + if (head == null) { + return; + } + ArrayList list = solutions.get(height - 1 - level); + list.add(head.Data); + levelOrderHelper(solutions, level + 1, height, head.Left); + levelOrderHelper(solutions, level + 1, height, head.Right); + } + + public static void main(String[] args) { + Q13_BinaryTreeLevelOrderTraversal2 q13 = new Q13_BinaryTreeLevelOrderTraversal2(); + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + ArrayList> solutions = q13.levelOrderBottom(root); + for (ArrayList arrayList : solutions) { + for (Integer integer : arrayList) { + System.out.print(integer + ","); + } + System.out.println(); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q14_MaximumPathSum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q14_MaximumPathSum.java new file mode 100644 index 0000000..c9957c1 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q14_MaximumPathSum.java @@ -0,0 +1,42 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q14_MaximumPathSum { + + public int maxPathSum(BinaryTreeNode root) { + return maxPathSumHelper(root).RouteVal; + } + + private Wrapper maxPathSumHelper(BinaryTreeNode root) { + if (root == null) { + return new Wrapper(0, 0); + } + Wrapper l = maxPathSumHelper(root.Left); + Wrapper r = maxPathSumHelper(root.Right); + int depthval = Math.max(l.DepthVal, r.DepthVal) + root.Data; + int routeval = l.DepthVal + r.DepthVal + root.Data; + Wrapper wr = new Wrapper(depthval, routeval); + return wr; + } + + class Wrapper { + + public int DepthVal; + public int RouteVal; + + public Wrapper(int _depthval, int _routeval) { + this.DepthVal = _depthval; + this.RouteVal = _routeval; + } + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + int distance = new Q14_MaximumPathSum().maxPathSum(root); + System.out.println(distance); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q15_BinaryTreeZigzagLevelOrderTraversal.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q15_BinaryTreeZigzagLevelOrderTraversal.java new file mode 100644 index 0000000..7c5e8dd --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q15_BinaryTreeZigzagLevelOrderTraversal.java @@ -0,0 +1,85 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; +import java.util.Iterator; + +public class Q15_BinaryTreeZigzagLevelOrderTraversal { + + public ArrayList> zigzagLevelOrder(BinaryTreeNode root) { + ArrayList> solutions = new ArrayList>(); + int height = getHeight(root), i = 0; + for (; i < height; ++i) { + solutions.add(new ArrayList()); + } + zigzagLevelOrderHelper(root, 0, solutions); + return solutions; + } + + private void zigzagLevelOrderHelper(BinaryTreeNode root, int level, ArrayList> solutions) { + if (root == null) { + return; + } + zigzagLevelOrderHelper(root.Left, level + 1, solutions); + zigzagLevelOrderHelper(root.Right, level + 1, solutions); + + ArrayList list = solutions.get(level); + if (level % 2 == 0) { + list.add(root.Data); + } else { + list.add(0, root.Data); + } + } + + private int getHeight(BinaryTreeNode root) { + if (root == null) { + return 0; + } + int l = getHeight(root.Left); + int r = getHeight(root.Right); + return Math.max(l, r) + 1; + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + ArrayList> solutions = new Q15_BinaryTreeZigzagLevelOrderTraversal().zigzagLevelOrderMy(root); + for (Iterator> it = solutions.iterator(); it.hasNext();) { + ArrayList arrayList = it.next(); + System.out.print("["); + for (Iterator it1 = arrayList.iterator(); it1.hasNext();) { + Integer integer = it1.next(); + System.out.print(integer + " "); + } + System.out.print("]"); + System.out.println(); + } + } + + public ArrayList> zigzagLevelOrderMy(BinaryTreeNode root) { + ArrayList> solutions = new ArrayList<>(); + MyHelper(solutions, root, 0); + return solutions; + } + + void MyHelper(ArrayList> solutions, BinaryTreeNode head, int level) { + if (head == null) { + return; + } + + if (level == solutions.size()) { + ArrayList solution = new ArrayList<>(); + solutions.add(solution); + } + if (level % 2 == 0) { + solutions.get(level).add(head.Data); + } else { + solutions.get(level).add(0, head.Data); + } + + MyHelper(solutions, head.Left, level + 1); + MyHelper(solutions, head.Right, level + 1); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q16_ClimbingStairs.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q16_ClimbingStairs.java new file mode 100644 index 0000000..a5115f4 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q16_ClimbingStairs.java @@ -0,0 +1,31 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.HashMap; + +public class Q16_ClimbingStairs { + + HashMap cache = new HashMap<>(); + + public int climbStairs(int n) { + if (n == 0) { + return 1; + } else if (n < 0) { + return 0; + } + if (cache.containsKey(n)) { + return cache.get(n); + } + int ways = climbStairs(n - 2) + climbStairs(n - 1); + cache.put(n, ways); + return ways; + } + + public static void main(String[] args) { + Q16_ClimbingStairs q16 = new Q16_ClimbingStairs(); + int ways = q16.climbStairs(2); + System.out.println(ways); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q17_CombinationSum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q17_CombinationSum.java new file mode 100644 index 0000000..824f882 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q17_CombinationSum.java @@ -0,0 +1,175 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + +public class Q17_CombinationSum { + + //wrong + public ArrayList> combinationSumDP(int[] candidates, int target) { + HashMap>> solutions = new HashMap>>(); + int candidates_index, candidate_length = candidates.length; + for (int current_sum = 1; current_sum <= target; current_sum++) { + for (candidates_index = 0; candidates_index < candidate_length; candidates_index++) { + if (current_sum < candidates[candidates_index]) { + continue; + } else if (current_sum == candidates[candidates_index]) { + if (solutions.containsKey(current_sum)) { + ArrayList temp_list = new ArrayList(); + temp_list.add(candidates[candidates_index]); + solutions.get(current_sum).add(temp_list); + } else { + ArrayList> temp_solution = new ArrayList>(); + ArrayList temp_list = new ArrayList(); + temp_list.add(candidates[candidates_index]); + temp_solution.add(temp_list); + solutions.put(current_sum, temp_solution); + } + continue; + } + int remaining_sum = current_sum - candidates[candidates_index]; + if (solutions.containsKey(remaining_sum)) { + ArrayList> prior_solution = solutions.get(remaining_sum); + if (solutions.containsKey(current_sum)) { + ArrayList> temp_solution = new ArrayList>(); + for (ArrayList prior_list : prior_solution) { + if (prior_list.get(prior_list.size() - 1) > candidates[candidates_index]) { + continue; + } + ArrayList temp_list = new ArrayList(); + temp_list.addAll(prior_list); + temp_list.add(candidates[candidates_index]); + temp_solution.add(temp_list); + } + solutions.get(current_sum).addAll(temp_solution); + } else { + ArrayList> temp_solution = new ArrayList>(); + for (ArrayList prior_list : prior_solution) { + if (prior_list.get(prior_list.size() - 1) >= candidates[candidates_index]) { + continue; + } + ArrayList temp_list = new ArrayList(); + temp_list.addAll(prior_list); + temp_list.add(candidates[candidates_index]); + temp_solution.add(temp_list); + } + solutions.put(current_sum, temp_solution); + } + } else { + continue; + } + } + } + + return solutions.get(target); + } + + public ArrayList> combinationSumEx(int[] candidates, int target) { + ArrayList> solutions = new ArrayList>(); + HashSet cache = new HashSet(); + combinationSumHelper(new ArrayList(), target, candidates.length - 1, candidates, solutions, cache); + return solutions; + } + + private void combinationSumHelper(ArrayList current_solution, int remaining, int candidate_index, int[] candidates, ArrayList> solutions, HashSet cache) { + if (remaining == 0) { + StringBuilder sb = new StringBuilder(); + for (int num : current_solution) { + sb.append(num); + } + if (!cache.contains(sb.toString())) { + solutions.add(current_solution); + } + cache.add(sb.toString()); + } + if (candidate_index < 0) { + return; + } + int current_candidate_val = candidates[candidate_index]; + for (int i = 0; remaining - i * current_candidate_val >= 0; i++) { + ArrayList next_solution = (ArrayList) current_solution.clone(); + for (int n = 0; n < i; n++) { + next_solution.add(current_candidate_val); + } + combinationSumHelper(next_solution, remaining - i * current_candidate_val, candidate_index - 1, candidates, solutions, cache); + } + } + + public static void main(String[] args) { + int[] candidates = {1, 1, 2, 5, 6, 7, 10}; + int target = 8; + ArrayList> solutions = new Q17_CombinationSum().combinationSum(candidates, target); + for (Iterator> it = solutions.iterator(); it.hasNext();) { + ArrayList arrayList = it.next(); + for (Iterator it1 = arrayList.iterator(); it1.hasNext();) { + Integer integer = it1.next(); + System.out.print(integer + " "); + } + System.out.println(); + } + + int[] people = TestUtil.generateArray(38, 100, false); + java.util.Arrays.sort(people); + long l1 = System.currentTimeMillis(); + ArrayList> solutions1 = new Q17_CombinationSum().combinationSumDP(people, 50); + long l2 = System.currentTimeMillis(); + ArrayList> solutions2 = new Q17_CombinationSum().combinationSumEx(people, 50); + long l3 = System.currentTimeMillis(); + ArrayList> solutions3 = new Q17_CombinationSum().combinationSum(people, 50); + long l4 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2, span3 = l4 - l3; + System.out.println(solutions1.size() + " Cost " + span1); + System.out.println(solutions2.size() + " Cost " + span2); + System.out.println(solutions3.size() + " Cost " + span3); + } + + //my way + public ArrayList> combinationSum(int[] candidates, int target) { + //REMOVE DUPLICATE + ArrayList without_dup = new ArrayList<>(); + for (int i = 1; i < candidates.length; i++) { + if (candidates[i] != candidates[i - 1]) { + without_dup.add(candidates[i - 1]); + if (i == candidates.length - 1) { + without_dup.add(candidates[i]); + } + } + } + ArrayList>[] DP = new ArrayList[target + 1]; + for (int cur_target = 1; cur_target <= target; cur_target++) { + DP[cur_target] = new ArrayList<>(); + /*if (cur_target < candidates[0]) { + continue; + }*/ + for (int i = 0; i < without_dup.size(); i++) { + if (cur_target < without_dup.get(i)) { + break; + } else if (cur_target == without_dup.get(i)) { + ArrayList solution = new ArrayList<>(); + solution.add(cur_target); + DP[cur_target].add(solution); + break; + } + int remaining = cur_target - without_dup.get(i); + if (DP[remaining].size() > 0) { + for (ArrayList list : DP[remaining]) { + if (list.get(list.size() - 1) > without_dup.get(i)) { + continue; + } + ArrayList temp = new ArrayList<>(); + temp.addAll(list); + temp.add(without_dup.get(i)); + DP[cur_target].add(temp); + } + } + } + } + return DP[target]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q18_CombinationSum2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q18_CombinationSum2.java new file mode 100644 index 0000000..e45b295 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q18_CombinationSum2.java @@ -0,0 +1,128 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class Q18_CombinationSum2 { + + public ArrayList> combinationSumEx(int[] candidates, int target) { + ArrayList> solutions = new ArrayList>(); + HashSet cache = new HashSet(); + combinationSumHelper(new ArrayList(), target, candidates.length - 1, candidates, solutions, cache); + return solutions; + } + + private void combinationSumHelper(ArrayList current_solution, int remaining, int candidate_index, int[] candidates, ArrayList> solutions, HashSet cache) { + if (remaining == 0) { + StringBuilder sb = new StringBuilder(); + for (int num : current_solution) { + sb.append(num); + } + if (!cache.contains(sb.toString())) { + solutions.add(current_solution); + } + cache.add(sb.toString()); + } + if (candidate_index < 0) { + return; + } + int current_candidate_val = candidates[candidate_index]; + for (int i = 0; i <= 1; i++) { + ArrayList next_solution = (ArrayList) current_solution.clone(); + if (i == 1) { + next_solution.add(current_candidate_val); + } + combinationSumHelper(next_solution, remaining - i * current_candidate_val, candidate_index - 1, candidates, solutions, cache); + } + } + + public static void main(String[] args) { + int[] candidates = {1, 1, 2, 5, 6, 7, 10}; + int target = 8; + ArrayList> solutions = new Q18_CombinationSum2().combinationSum(candidates, target); + for (Iterator> it = solutions.iterator(); it.hasNext();) { + ArrayList arrayList = it.next(); + for (Iterator it1 = arrayList.iterator(); it1.hasNext();) { + Integer integer = it1.next(); + System.out.print(integer + " "); + } + System.out.println(); + } + + int[] people = TestUtil.generateArray(20, 10, false); + java.util.Arrays.sort(people); + long l1 = System.currentTimeMillis(); + ArrayList> solutions1 = new Q18_CombinationSum2().combinationSumEx(people, 9); + long l2 = System.currentTimeMillis(); + ArrayList> solutions2 = new Q18_CombinationSum2().combinationSum(people, 9); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(solutions1.size() + " Cost " + span1); + System.out.println(solutions2.size() + " Cost " + span2); + } + + //my way + public ArrayList> combinationSum(int[] candidates, int target) { + //RD table + HashMap candidiate_map = new HashMap<>(); + for (int i = 0; i < candidates.length; i++) { + if (!candidiate_map.containsKey(candidates[i])) { + candidiate_map.put(candidates[i], 1); + } else { + int val = candidiate_map.get(candidates[i]); + candidiate_map.put(candidates[i], val + 1); + } + } + ArrayList>[] DP = new ArrayList[target + 1]; + for (int cur_target = 1; cur_target <= target; cur_target++) { + DP[cur_target] = new ArrayList<>(); + Set set = candidiate_map.keySet(); + for (Integer i : set) { + if (i > cur_target) { + break; + } else if (i == cur_target) { + ArrayList solution = new ArrayList<>(); + solution.add(cur_target); + DP[cur_target].add(solution); + break; + } + + int remaining = cur_target - i; + if (DP[remaining] != null && DP[remaining].size() > 0) { + for (ArrayList list : DP[remaining]) { + if (list.get(list.size() - 1) > i) { + continue; + } + if (!enoughInMap(candidiate_map, list, i)) { + continue; + } + ArrayList solution = new ArrayList<>(); + solution.addAll(list); + solution.add(i); + DP[cur_target].add(solution); + } + } + } + } + return DP[target]; + } + + private boolean enoughInMap(HashMap candidiate_map, ArrayList list, int key) { + int count = candidiate_map.get(key); + for (int i = list.size() - 1; i >= 0; i--) { + if (list.get(i) == key) { + --count; + } else { + break; + } + } + return count > 0; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q19_Combinations.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q19_Combinations.java new file mode 100644 index 0000000..a7c45fb --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q19_Combinations.java @@ -0,0 +1,113 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.Iterator; + +public class Q19_Combinations { + + public ArrayList> combine(int n, int k) { + ArrayList>> solutions = new ArrayList>>(2); + solutions.add(new ArrayList>()); + solutions.add(new ArrayList>()); + int i = 1; + for (; i <= n; ++i) { + ArrayList temp_list = new ArrayList<>(); + temp_list.add(i); + solutions.get(0).add(temp_list); + } + for (i = 2; i <= k; ++i) { + ArrayList> current_solution = solutions.get((i) % 2); + ArrayList> last_solution = solutions.get((i + 1) % 2); + ArrayList> next_solution = new ArrayList>(); + for (ArrayList list : current_solution) { + int last_big = list.get(list.size() - 1); + for (int val = 1; val <= n; ++val) { + if (val > last_big) { + ArrayList temp_list = new ArrayList<>(); + temp_list.addAll(list); + temp_list.add(val); + next_solution.add(temp_list); + } + } + } + last_solution.clear(); + last_solution.addAll(next_solution); + } + return solutions.get(i % 2); + } + + public ArrayList> combineEx(int n, int k) { + ArrayList> solutions = new ArrayList>(); + combineHelper(0, 1, k, n, new ArrayList(), solutions); + return solutions; + } + + private void combineHelper(int last_val, int current_bit, int k, int n, ArrayList solution, ArrayList> solutions) { + if (current_bit > k) { + solutions.add(solution); + return; + } + int val = 1; + for (; val <= n; ++val) { + if (val > last_val) { + ArrayList next_solution = (ArrayList) solution.clone(); + next_solution.add(val); + combineHelper(val, current_bit + 1, k, n, next_solution, solutions); + } + } + } + + public static void main(String[] args) { + ArrayList> solutions = new Q19_Combinations().combineMy(4, 2); + for (Iterator> it = solutions.iterator(); it.hasNext();) { + ArrayList arrayList = it.next(); + for (Iterator it1 = arrayList.iterator(); it1.hasNext();) { + Integer integer = it1.next(); + System.out.print(integer + " "); + } + System.out.println(); + } + + int k = 15, n = 25; + long l1 = System.currentTimeMillis(); + ArrayList> solutions1 = new Q19_Combinations().combine(n, k); + long l2 = System.currentTimeMillis(); + ArrayList> solutions2 = new Q19_Combinations().combineEx(n, k); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(solutions1.size() + " Cost " + span1); + System.out.println(solutions2.size() + " Cost " + span2); + } + + //my way + public ArrayList> combineMy(int n, int k) { + ArrayList>[] solutions = new ArrayList[2]; + solutions[0] = new ArrayList<>(); + solutions[1] = new ArrayList<>(); + int i = 0; + for (int j = 1; j <= n; j++) { + ArrayList solution = new ArrayList<>(); + solution.add(j); + solutions[0].add(solution); + } + while (++i < k) { + ArrayList> pre = solutions[(i + 1) % 2]; + ArrayList> cur = solutions[i % 2]; + cur.clear(); + for (ArrayList arrayList : pre) { + for (int j = 1; j <= n; j++) { + if (arrayList.get(arrayList.size() - 1) < j) { + ArrayList solution = new ArrayList<>(); + solution.addAll(arrayList); + solution.add(j); + cur.add(solution); + } + } + } + } + return solutions[(i + 1) % 2]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q1_3Sum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q1_3Sum.java new file mode 100644 index 0000000..b4451e3 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q1_3Sum.java @@ -0,0 +1,101 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; + +public class Q1_3Sum { + + public ArrayList> threeSum(int[] num) { + java.util.Arrays.sort(num); + ArrayList> solutions = new ArrayList<>(); + HashSet cache = new HashSet<>(); + int length = num.length, i = 0; + for (; i < length - 3; i++) { + int s = i + 1; + int e = length - 1; + while (s < e) { + int current_sum = num[i] + num[s] + num[e]; + String key = String.valueOf(num[e]) + String.valueOf(num[s]) + String.valueOf(num[i]); + if (cache.contains(key)) { + --e; + ++s; + } else if (current_sum == 0) { + ArrayList solution = new ArrayList<>(3); + solution.add(num[e]); + solution.add(num[s]); + solution.add(num[i]); + solutions.add(solution); + cache.add(key); + --e; + ++s; + } else if (current_sum > 0) { + --e; + } else { + ++s; + } + } + } + + return solutions; + } + + //My way + public ArrayList> threeSumEx(int[] num) { + java.util.Arrays.sort(num); + ArrayList> solutions = new ArrayList<>(); + HashSet cache = new HashSet<>(); + int length = num.length, i, s, e; + for (i = 0; i < length - 3; i++) { + s = i + 1; + e = length - 1; + while (s < e) { + if (num[s] + num[e] + num[i] == 0) { + if (cache.contains(String.valueOf(num[i])+String.valueOf(num[s])+String.valueOf(num[e]))) { + continue; + } + cache.add(String.valueOf(num[i])+String.valueOf(num[s])+String.valueOf(num[e])); + ArrayList solution = new ArrayList<>(); + solution.add(num[i]); + solution.add(num[s]); + solution.add(num[e]); + solutions.add(solution); + ++s;--e; + } else if (num[s] + num[e] + num[i] < 0) { + ++s; + } else if (num[s] + num[e] + num[i] > 0) { + --e; + } + } + } + return solutions; + } + + public static void main(String[] args) { + int[] num = {-1, -1, 0, 1, -4, 2}; + ArrayList> solutions = new Q1_3Sum().threeSum(num); + for (Iterator> it = solutions.iterator(); it.hasNext();) { + ArrayList arrayList = it.next(); + for (Iterator it1 = arrayList.iterator(); it1.hasNext();) { + System.out.print(it1.next()); + System.out.print(" "); + } + System.out.println(); + } + + //test1 + int[] arr = Util.TestUtil.generateArray(30); + long t1 = System.currentTimeMillis(); + ArrayList> solutions1 = new Q1_3Sum().threeSum(arr); + long t2 = System.currentTimeMillis(); + ArrayList> solutions2 = new Q1_3Sum().threeSumEx(arr); + long t3 = System.currentTimeMillis(); + long span1 = t2 - t1; + long span2 = t3 - t2; + System.out.println(solutions1.size() + " Cost " + span1); + System.out.println(solutions2.size() + " Cost " + span2); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q20_ConstructBinaryTreeFromMidPostTraversal.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q20_ConstructBinaryTreeFromMidPostTraversal.java new file mode 100644 index 0000000..ade768f --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q20_ConstructBinaryTreeFromMidPostTraversal.java @@ -0,0 +1,62 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q20_ConstructBinaryTreeFromMidPostTraversal { + + public BinaryTreeNode buildTree(int[] inorder, int[] postorder) { + int length = inorder.length; + return buildTreeHelper(0, length - 1, 0, length - 1, inorder, postorder); + } + + private BinaryTreeNode buildTreeHelper(int post_s, int post_e, int in_s, int in_e, int[] inorder, int[] postorder) { + if (in_s > in_e) { + return null; + } + int root_val = postorder[post_e]; + int i = in_s; + for (i = in_s; i <= in_e; ++i) { + if (inorder[i] == root_val) { + break; + } + } + int left_len = i - in_s; + BinaryTreeNode root = new BinaryTreeNode<>(root_val); + root.Left = buildTreeHelper(post_s, post_s + left_len - 1, in_s, i - 1, inorder, postorder); + root.Right = buildTreeHelper(post_s + left_len, post_e - 1, i + 1, in_e, inorder, postorder); + return root; + } + + public static void main(String[] args) { + int[] inorder = {2, 5, 7, 10, 15}; + int[] postorder = {2, 7, 5, 15, 10}; + BinaryTreeNode root = new Q20_ConstructBinaryTreeFromMidPostTraversal().buildTreeMy(inorder, postorder); + System.out.print(root); + } + + //my way + public BinaryTreeNode buildTreeMy(int[] inorder, int[] postorder) { + int length = inorder.length; + return buildTreeHelperMy(0, length - 1, 0, length - 1, inorder, postorder); + } + + private BinaryTreeNode buildTreeHelperMy(int post_s, int post_e, int in_s, int in_e, int[] inorder, int[] postorder) { + if (in_s > in_e || post_e < 0 || post_e >= inorder.length) { + return null; + } + BinaryTreeNode node = new BinaryTreeNode<>(postorder[post_e]); + int len = 0; + for (int i = in_s; i <= in_e; i++) { + if (inorder[i] == postorder[post_e]) { + break; + } + ++len; + } + node.Left = buildTreeHelperMy(post_s, post_s + len - 1, in_s, in_s + len - 1, inorder, postorder); + node.Right = buildTreeHelperMy(post_s + len, post_e - 1, in_s + len + 1, in_e, inorder, postorder); + return node; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q21_ConstructBinaryTreeFromPreMidTraversal.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q21_ConstructBinaryTreeFromPreMidTraversal.java new file mode 100644 index 0000000..290112d --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q21_ConstructBinaryTreeFromPreMidTraversal.java @@ -0,0 +1,62 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q21_ConstructBinaryTreeFromPreMidTraversal { + + public BinaryTreeNode buildTree(int[] preorder, int[] inorder) { + int length = preorder.length; + return buildTreeHelper(0, length - 1, 0, length - 1, preorder, inorder); + } + + private BinaryTreeNode buildTreeHelper(int pre_s, int pre_e, int in_s, int in_e, int[] preorder, int[] inorder) { + if (in_s > in_e) { + return null; + } + int root_val = preorder[pre_s]; + int i = in_s; + for (i = in_s; i <= in_e; ++i) { + if (inorder[i] == root_val) { + break; + } + } + int left_len = i - in_s; + BinaryTreeNode root = new BinaryTreeNode<>(root_val); + root.Left = buildTreeHelper(pre_s + 1, pre_s + left_len, in_s, i - 1, preorder, inorder); + root.Right = buildTreeHelper(pre_s + left_len + 1, pre_e, i + 1, in_e, preorder, inorder); + return root; + } + + public static void main(String[] args) { + int[] preorder = {2, 1, 4, 3, 5}; + int[] inorder = {1, 2, 3, 4, 5}; + BinaryTreeNode root = new Q21_ConstructBinaryTreeFromPreMidTraversal().buildTreeMy(preorder, inorder); + System.out.print(root); + } + + //my way + public BinaryTreeNode buildTreeMy(int[] preorder, int[] inorder) { + int length = inorder.length; + return buildTreeHelperMy(0, length - 1, 0, length - 1, preorder, inorder); + } + + private BinaryTreeNode buildTreeHelperMy(int pre_s, int pre_e, int in_s, int in_e, int[] preorder, int[] inorder) { + if (in_s > in_e || pre_s < 0 || pre_e >= inorder.length) { + return null; + } + BinaryTreeNode node = new BinaryTreeNode<>(preorder[pre_s]); + int len = 0; + for (int i = in_s; i <= in_e; i++) { + if (inorder[i] == preorder[pre_s]) { + break; + } + ++len; + } + node.Left = buildTreeHelperMy(pre_s + 1, pre_s + 1 + len - 1, in_s, in_s + len - 1, preorder,inorder); + node.Right = buildTreeHelperMy(pre_s + len + 1, pre_e - 1, in_s + len + 1, in_e, preorder,inorder); + return node; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q22_ContainerWithMostWater.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q22_ContainerWithMostWater.java new file mode 100644 index 0000000..c062540 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q22_ContainerWithMostWater.java @@ -0,0 +1,48 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q22_ContainerWithMostWater { + + public int maxArea(int[] height) { + int s = 0, length = height.length, e = length - 1; + int MaxArea = Integer.MIN_VALUE; + while (s < e) { + int Height = Math.min(height[s], height[e]); + int Area = Height * (e - s + 1); + MaxArea = Area > MaxArea ? Area : MaxArea; + if (height[s] > height[e]) { + while (height[e] >= height[--e]) { + } + } else { + while (height[s] >= height[++s]) { + } + } + } + return MaxArea; + } + + public static void main(String[] args) { + int[] height = {1, 2, 4, 3}; + int MaxArea = new Q22_ContainerWithMostWater().maxAreaMy(height); + System.out.println(MaxArea); + } + + public int maxAreaMy(int[] height) { + int s = 0, e = height.length - 1; + int max = Integer.MIN_VALUE; + while (s < e) { + int cur = (e - s + 1) * Math.min(height[s], height[e]); + max = Math.max(max, cur); + if (height[s] > height[e]) { + while (e >= 0 && height[e] >= height[--e]) { + } + } else { + while (s < height.length && height[s] >= height[++s]) { + } + } + } + return max; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q23_ConvertArrayToBinaryTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q23_ConvertArrayToBinaryTree.java new file mode 100644 index 0000000..7bae435 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q23_ConvertArrayToBinaryTree.java @@ -0,0 +1,23 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q23_ConvertArrayToBinaryTree { + + public BinaryTreeNode sortedArrayToBST(int[] num, int s, int e) { + if (s > e) { + return null; + } + int m = s + (e - s) / 2; + BinaryTreeNode node = new BinaryTreeNode<>(num[m]); + node.Left = sortedArrayToBST(num, s, m - 1); + node.Right = sortedArrayToBST(num, m + 1, e); + return node; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q24_ConvertLinkedListToBinaryTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q24_ConvertLinkedListToBinaryTree.java new file mode 100644 index 0000000..82289af --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q24_ConvertLinkedListToBinaryTree.java @@ -0,0 +1,74 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import Util.LinkedListNode; + +public class Q24_ConvertLinkedListToBinaryTree { + + public BinaryTreeNode sortedListToBST(LinkedListNode head) { + int s = 0, e = 0; + LinkedListNode runner = head; + while (runner != null) { + ++e; + runner = runner.Next; + } + return sortedListToBSTHelper(new Wrapper(head), s, e - 1); + } + + private BinaryTreeNode sortedListToBSTHelper(Wrapper wr, int s, int e) { + if (s > e) { + return null; + } + int m = s + (e - s) / 2; + BinaryTreeNode Left = sortedListToBSTHelper(wr, s, m - 1); + BinaryTreeNode parent = new BinaryTreeNode<>(wr.Node.Data); + parent.Left = Left; + wr.Node = wr.Node.Next; + parent.Right = sortedListToBSTHelper(wr, m + 1, e); + return parent; + } + + class Wrapper { + + LinkedListNode Node; + + public Wrapper(LinkedListNode _node) { + this.Node = _node; + } + } + + public static void main(String[] args) { + LinkedListNode list = LinkedListNode.getSampleLinkedList(); + BinaryTreeNode root = new Q24_ConvertLinkedListToBinaryTree().sortedListToBSTMy(list); + } + + //my way + public BinaryTreeNode sortedListToBSTMy(LinkedListNode head) { + int len = head.getLength(); + wm = new WrapperMy(); + wm.node = head; + BinaryTreeNode node = sortedListToBSTMyHelper(0, len - 1); + return node; + } + WrapperMy wm = null; + + private BinaryTreeNode sortedListToBSTMyHelper(int s, int e) { + if (s > e) { + return null; + } + int m = s + (e - s) / 2; + BinaryTreeNode node = new BinaryTreeNode<>(-1); + node.Left = sortedListToBSTMyHelper(s, m - 1); + node.Data = wm.node.Data; + wm.node = wm.node.Next; + node.Right = sortedListToBSTMyHelper(m + 1, e); + return node; + } + + class WrapperMy { + LinkedListNode node; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q25_CountAndSay.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q25_CountAndSay.java new file mode 100644 index 0000000..5b4566c --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q25_CountAndSay.java @@ -0,0 +1,51 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q25_CountAndSay { + + public String countAndSay(int n) { + StringBuilder sb = new StringBuilder(); + int last_digit = -1, digit = -1, count = 0; + while (n > 0) { + digit = n % 10; + if (last_digit >= 0 && last_digit != digit) { + sb.insert(0, count).insert(0, last_digit).insert(0, " "); + count = 1; + } else { + ++count; + } + last_digit = digit; + n = n / 10; + } + if (last_digit >= 0) { + sb.insert(0, count).insert(0, last_digit); + } + return sb.toString(); + } + + public static void main(String[] args) { + int num = 1223334445; + String text = new Q25_CountAndSay().countAndSayMy(num); + System.out.println(text); + } + + public String countAndSayMy(int n) { + StringBuilder sb = new StringBuilder(); + int last_digit = -1, count = 0; + while (n > 0) { + int digit = n % 10; + if (last_digit != -1 && last_digit != digit) { + sb.insert(0, " ").insert(0, count).insert(0, last_digit); + count = 1; + } else { + ++count; + } + last_digit = digit; + n /= 10; + } + sb.insert(0, " ").insert(0, count).insert(0, last_digit); + return sb.toString(); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q26_DecodeWays.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q26_DecodeWays.java new file mode 100644 index 0000000..d02be22 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q26_DecodeWays.java @@ -0,0 +1,137 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; +import java.util.HashMap; + +public class Q26_DecodeWays { + + public int numDecodingsDP2(String s) { + int[] cache = new int[3]; + cache[0] = 1; + if (s.charAt(1) <= '6' && s.charAt(1) > '0' + && s.charAt(0) <= '2' && s.charAt(0) >= '1') { + cache[1] = 2; + } else { + cache[1] = 1; + } + int i = 2, length = s.length(); + int index = i % 3; + int last_index = (i - 1) % 3; + int last_index2 = (i - 2) % 3; + for (; i < length; ++i) { + index = i % 3; + last_index = (i - 1) % 3; + last_index2 = (i - 2) % 3; + int count = 0; + if (s.charAt(i) == '0') { + count += cache[last_index2]; + } else { + count += cache[last_index]; + if (s.charAt(i) <= '6' && s.charAt(i) > '0' + && s.charAt(i - 1) <= '2' && s.charAt(i - 1) >= '1') { + count += cache[last_index2]; + } + } + cache[index] = count; + } + return cache[(i - 1) % 3]; + } + + public int numDecodingsDP(String s) { + HashMap cache = new HashMap<>(); + cache.put(s.substring(0, 1), 1); + cache.put("", 1); + int length = s.length(), i = 2; + for (; i <= length; ++i) { + String current_str = s.substring(0, i); + char c = current_str.charAt(i - 1); + if (c == '0') { + cache.put(current_str, cache.get(current_str.substring(0, i - 2))); + } else { + int count = cache.get(current_str.substring(0, i - 1)); + if (s.charAt(i - 1) >= '0' && s.charAt(i - 1) <= '6' + && s.charAt(i - 2) >= '1' && s.charAt(i - 2) <= '2') { + count += cache.get(current_str.substring(0, i - 2)); + } + cache.put(current_str, count); + } + } + return cache.get(s); + } + + public int numDecodingsEx(String s) { + return numDecodingsHelper(s, 0); + } + + private int numDecodingsHelper(String s, int i) { + if (i == s.length() - 2) { + if (s.charAt(i) >= '1' && s.charAt(i) <= '2' && s.charAt(1 + i) <= '6' && s.charAt(1 + i) >= '0') { + return 2; + } else { + return 1; + } + } else if (i == s.length() - 1) { + return 1; + } else if (i >= s.length()) { + return 0; + } + int ways = 0; + if (s.charAt(i + 1) == '0') { + ways += numDecodingsHelper(s, i + 2); + } else { + ways += numDecodingsHelper(s, i + 1); + } + if (i + 1 < s.length() && s.charAt(i) <= '6' + && s.charAt(i + 1) <= '2' && s.charAt(i + 1) >= '1' + && s.charAt(i) > '0') { + ways += numDecodingsHelper(s, i + 2); + } + return ways; + } + + public static void main(String[] args) { + String text = "11231213112312312312310021211213";//TestUtil.generateArrayString(20, 9); + long l1 = System.currentTimeMillis(); + int ways = new Q26_DecodeWays().numDecodingsEx(text); + long l2 = System.currentTimeMillis(); + int ways2 = new Q26_DecodeWays().numDecodingsMy(text); + long l3 = System.currentTimeMillis(); + int ways3 = new Q26_DecodeWays().numDecodingsDP2(text); + long l4 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2, span3 = l4 - l3; + System.out.println("EX:" + ways + " Cost " + span1); + System.out.println("DP:" + ways2 + " Cost " + span2); + System.out.println("DP2:" + ways3 + " Cost " + span3); + } + + //most correct one + public int numDecodingsMy(String s) { + int len = s.length(), index; + int[] tab = new int[len]; + if (s.charAt(0) >= '1' && s.charAt(0) <= '9') { + tab[0] = 1; + } else { + tab[0] = 0; + } + for (index = 1; index < len; index++) { + char ch = s.charAt(index); + char last_ch = s.charAt(index - 1); + int count = 0; + if (ch >= '1' && ch <= '9') { + count += tab[index - 1]; + } + if (last_ch >= '1' && last_ch <= '2' && ch >= '0' && ch <= '6') { + if (index - 2 >= 0) { + count += tab[index - 2]; + } else { + count += 1; + } + } + tab[index] = count; + } + return tab[len - 1]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q27_DistinctSubsequences.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q27_DistinctSubsequences.java new file mode 100644 index 0000000..5f55e67 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q27_DistinctSubsequences.java @@ -0,0 +1,73 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 19, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q27_DistinctSubsequences { + + int numDistinct(String S, String T) { + int s_i = 0, t_i = 0, s_length = S.length(), t_length = T.length(), i, j; + int[][] cache = new int[s_length + 1][t_length + 1]; + cache[0][0] = 1; + for (i = 1; i < s_length + 1; i++) { + cache[i][0] = 0; + } + for (i = 1; i < t_length + 1; i++) { + cache[0][i] = 0; + } + for (i = 1; i < s_length + 1; i++) { + for (j = 1; j < t_length + 1; j++) { + if (S.charAt(i - 1) == T.charAt(j - 1)) { + cache[i][j] = 0; + for (int k = 0; k < i; k++) { + cache[i][j] += cache[k][j - 1]; + } + } else { + cache[i][j] = 0; + } + } + } + int sum = 0; + for (i = 0; i < s_length + 1; ++i) { + sum += cache[i][t_length]; + } + return sum; + } + + public static void main(String[] args) { + String S = "abab"; + String T = "ab"; + int num = new Q27_DistinctSubsequences().numDistinct(S, T); + System.out.println(num); + } + + //my way WRONG! + int numDistinctMy(String S, String T) { + int s_len = S.length(), t_len = T.length(), i, j, k; + int[][] tab = new int[1 + s_len][1 + t_len]; + tab[0][0] = 1; + for (i = 1; i <= s_len; i++) { + tab[i][0] = 0; + } + for (i = 1; i <= t_len; i++) { + tab[0][i] = 0; + } + for (i = 1; i <= s_len; i++) { + for (j = 1; j <= t_len; j++) { + if (S.charAt(i - 1) == T.charAt(j - 1)) { + tab[i][j] = 0; + for (k = 0; k < j; k++) { + tab[i][j] += tab[k][j - 1]; + } + } else { + tab[i][j] = 0; + } + } + } + int sum = 0; + for (i = 0; i < s_len + 1; ++i) { + sum += tab[i][t_len]; + } + return sum; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q28_DivideTwoIntegers.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q28_DivideTwoIntegers.java new file mode 100644 index 0000000..3b09f8b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q28_DivideTwoIntegers.java @@ -0,0 +1,79 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 19, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q28_DivideTwoIntegers { + + int divide(int dividend, int divisor) { + boolean neg = false; + if (dividend < 0) { + neg = !neg; + dividend = toPos(dividend); + } + if (divisor < 0) { + neg = !neg; + divisor = toPos(divisor); + } + return divideHelper(dividend, divisor) * (neg ? -1 : 1); + + } + + int divideHelper(int dividend, int divisor) { + if (dividend < divisor) { + return 0; + } else if (dividend == divisor) { + return 1; + } + /* + if (dividend <= (divisor >> 1)) { + System.out.println("OverFlow"); + return 0; + } + if ((divisor << 1) <= divisor) { + System.out.println("OverFlow"); + return 0; + } + */ + int bit_count = 0; + int temp = divisor; + while (dividend > (temp << 1)) { + ++bit_count; + temp <<= 1; + /*if ((temp << 1) <= temp) { + System.out.println("OverFlow"); + //break; + }*/ + } + return divide(dividend - temp, divisor) + (1 << bit_count); + } + + int toPos(int n) { + return ~n + 1; + } + + public static void main(String[] args) { + System.out.println(new Q28_DivideTwoIntegers().toPos(100)); + int divident = 10; + int divisor = 3; + int result = new Q28_DivideTwoIntegers().divideMy(divident, divisor); + System.out.println(result); + System.out.println("Sample:" + divident / divisor); + } + + //my way + int divideMy(int dividend, int divisor) { + if (dividend == divisor) { + return 1; + } else if (dividend < divisor) { + return 0; + } + int count = 0; + int temp = divisor; + while (dividend > (temp << 1)) { + temp <<= 1; + count++; + } + return (1 << count) + divideMy(dividend - temp, divisor); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q29_EditDistance.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q29_EditDistance.java new file mode 100644 index 0000000..c7b240f --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q29_EditDistance.java @@ -0,0 +1,71 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 19, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q29_EditDistance { + + int minDistance(String word1, String word2) { + int w1_length = word1.length(); + int w2_length = word2.length(); + int[][] cache = new int[w1_length + 1][w2_length + 1]; + int i, j; + for (i = 0; i < w1_length + 1; ++i) { + cache[i][0] = i; + } + for (j = 0; j < w2_length; ++j) { + cache[0][j] = j; + } + for (i = 1; i < w1_length + 1; ++i) { + for (j = 1; j < w2_length + 1; ++j) { + int min = Math.min(Math.min(cache[i - 1][j], cache[i][j - 1]), cache[i - 1][j - 1]); + cache[i][j] = min + word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 1; + } + } + + return cache[w1_length][w2_length]; + } + + public static void main(String[] args) { + String word1 = "abc"; + String word2 = "aeec"; + int dis = new Q29_EditDistance().minDistanceMy(word1, word2); + System.out.println(dis); + } + + //my way + int minDistanceMy(String word1, String word2) { + int w1_len = word1.length(), w2_len = word2.length(), i, j; + int[][] tab = new int[w1_len][w2_len]; + if (word1.charAt(0) == word2.charAt(0)) { + tab[0][0] = 0; + } else { + tab[0][0] = 1; + } + for (i = 1; i < w1_len; i++) { + if (word1.charAt(i) == word2.charAt(0)) { + tab[i][0] = tab[i - 1][0]; + } else { + tab[i][0] = 1 + tab[i - 1][0]; + } + } + for (i = 1; i < w2_len; i++) { + if (word1.charAt(0) == word2.charAt(i)) { + tab[0][i] = tab[0][i - 1]; + } else { + tab[0][i] = 1 + tab[0][i - 1]; + } + } + for (i = 1; i < w1_len; i++) { + for (j = 1; j < w2_len; j++) { + int min = Math.min(Math.min(tab[i - 1][j], tab[i][j - 1]), tab[i - 1][j - 1]); + if (word1.charAt(i) == word2.charAt(j)) { + tab[i][j] = min; + } else { + tab[i][j] = 1 + min; + } + } + } + return tab[w1_len - 1][w2_len - 1]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q2_3SumClosest.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q2_3SumClosest.java new file mode 100644 index 0000000..582b2e0 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q2_3SumClosest.java @@ -0,0 +1,72 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q2_3SumClosest { + + public int threeSumClosest(int[] num, int target) { + java.util.Arrays.sort(num); + int length = num.length, l = 0, r = length - 1, m = l + 1; + int SmallestDistance = Integer.MAX_VALUE; + while (r - l > 1) { + int current_sum = num[l] + num[r]; + if (current_sum > target) { + m = l + 1; + } else if (current_sum < target) { + m = r - 1; + } + current_sum += num[m]; + int CurrentDistance = Math.abs(current_sum - target); + if (CurrentDistance < SmallestDistance) { + SmallestDistance = CurrentDistance; + } + if (current_sum == target) { + return 0; + } else if (current_sum > target) { + --r; + /*if (r == m) { + --m; + }*/ + } else { + ++l; + /*if (l == m) { + ++m; + }*/ + } + } + + return SmallestDistance; + } + + //My way actually the correct way + public int threeSumClosestEx(int[] num, int target) { + java.util.Arrays.sort(num); + int cloest = Integer.MAX_VALUE; + int i, length = num.length; + for (i = 0; i < length - 3; i++) { + int s = i + 1; + int e = length - 1; + while (s < e) { + int sum = Math.abs(num[i] + num[s] + num[e]); + if (sum == target) { + return 0; + } else if (sum < target) { + ++s; + } else if (sum > target) { + --e; + } + + int temp = Math.abs(sum - target); + cloest = Math.min(cloest, temp); + } + } + return cloest; + } + + public static void main(String[] args) { + int[] num = {-1, 2, 1, -4}; + int SmallestDistance = new Q2_3SumClosest().threeSumClosestEx(num, 1); + System.out.print(SmallestDistance); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q30_FirstMissingPositive.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q30_FirstMissingPositive.java new file mode 100644 index 0000000..0face2c --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q30_FirstMissingPositive.java @@ -0,0 +1,48 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q30_FirstMissingPositive { + + public int firstMissingPositive(int[] A) { + int length = A.length, i = 0; + for (; i < length; ++i) { + if (A[i] > 0) { + //A[i] map to i+1 + int temp = A[A[i] - 1]; + A[A[i] - 1] = A[i]; + A[i] = temp; + } + } + for (i = 0; i < length; ++i) { + if (A[i] > 0 && A[i] != i + 1) { + return i + 1; + } + } + return Integer.MIN_VALUE; + } + + public static void main(String[] args) { + int[] A = {6, 4, 3, 1, 2, -1, -3}; + int missing = new Q30_FirstMissingPositive().firstMissingPositiveMy(A); + System.out.println(missing); + } + + //my way + public int firstMissingPositiveMy(int[] A) { + int len = A.length; + boolean[] helper = new boolean[len]; + for (int i = 0; i < len; i++) { + if (A[i] > 0) { + helper[A[i]] = true; + } + } + for (int i = 1; i < len; i++) { + if (!helper[i]) { + return i; + } + } + return -1; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q31_FlattenBinaryTreeToLinkedList.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q31_FlattenBinaryTreeToLinkedList.java new file mode 100644 index 0000000..d187e71 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q31_FlattenBinaryTreeToLinkedList.java @@ -0,0 +1,49 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q31_FlattenBinaryTreeToLinkedList { + + BinaryTreeNode LastNode = null; + + public void flatten(BinaryTreeNode root) { + if (root == null) { + return; + } + BinaryTreeNode left = root.Left; + BinaryTreeNode right = root.Right; + if (LastNode != null) { + LastNode.Right = root; + root.Right = null; + } + root.Left = null; + LastNode = root; + flatten(left); + flatten(right); + + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + new Q31_FlattenBinaryTreeToLinkedList().flattenMy(root); + } + BinaryTreeNode LastNodeMy = null; + + public void flattenMy(BinaryTreeNode root) { + if (root == null) { + return; + } + flattenMy(root.Left); + if (LastNodeMy != null) { + LastNodeMy.Right = root; + root.Parent = LastNodeMy; + } + root.Left =null; + LastNodeMy = root; + + flatten(root.Right); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q32_GenerateParentheses.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q32_GenerateParentheses.java new file mode 100644 index 0000000..954415b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q32_GenerateParentheses.java @@ -0,0 +1,39 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q32_GenerateParentheses { + + public static void main(String[] args) { + new Q32_GenerateParentheses().generateParenthesisMy(3); + } + + //my way + public void generateParenthesisMy(int n) { + presentation = new boolean[n * 2]; + generateHelper(n, n, 0); + } + boolean[] presentation; + + private void generateHelper(int left, int right, int index) { + if (left == 0 && right == 0) { + for (boolean b : presentation) { + if (b) { + System.out.print("["); + } else { + System.out.print("]"); + } + } + System.out.println(); + } + if (left > 0) { + presentation[index] = true; + generateHelper(left - 1, right, index + 1); + } + if (right > left) { + presentation[index] = false; + generateHelper(left, right - 1, index + 1); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q33_GreyCode.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q33_GreyCode.java new file mode 100644 index 0000000..94c2572 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q33_GreyCode.java @@ -0,0 +1,59 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.Iterator; + +public class Q33_GreyCode { + + public ArrayList grayCode(int n) { + int size = 1 << n, i = 0; + ArrayList solutions = new ArrayList<>(); + for (; i < size; ++i) { + int num = (i >> 1) ^ i; + solutions.add(num); + } + return solutions; + } + + //wrong + public ArrayList grayCodeEx(int n) { + int Biggest = (1 << n) - 1, current = 1; + ArrayList solutions = new ArrayList<>(); + solutions.add(0); + while (true) { + solutions.add(current); + if (current == Biggest) { + break; + } + current <<= 1; + current += 1; + } + current -= 1; + while (current > 0) { + solutions.add(current); + current <<= 1; + current -= (Biggest + 1); + } + return solutions; + } + + public static void main(String[] args) { + ArrayList solutions = new Q33_GreyCode().grayCode(3); + for (Iterator it = solutions.iterator(); it.hasNext();) { + Integer integer = it.next(); + System.out.println(integer + " " + Integer.toBinaryString(integer)); + } + int n = 2; + long l1 = System.currentTimeMillis(); + ArrayList solutions1 = new Q33_GreyCode().grayCode(n); + long l2 = System.currentTimeMillis(); + ArrayList solutions2 = new Q33_GreyCode().grayCodeEx(n); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(solutions1.size() + " Cost " + span1); + System.out.println(solutions2.size() + " Cost " + span2); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q34_StrStr.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q34_StrStr.java new file mode 100644 index 0000000..62c970e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q34_StrStr.java @@ -0,0 +1,164 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; + +public class Q34_StrStr { + + final String ErrorMessage = "Not Found!!!"; + + public String strStr(String haystack, String needle) { + int[] mapper = next(needle); + int i = 0, pos = 0, haystack_length = haystack.length(), needle_length = needle.length(); + while (i < haystack_length) { + while (haystack.charAt(i) == needle.charAt(pos)) { + ++i; + ++pos; + if (pos == needle_length) { + return haystack.substring(i - needle_length); + } + if (i == haystack_length) { + return ErrorMessage; + } + } + if (pos > 0) { + pos = mapper[pos - 1]; + } else { + pos = 0; + } + ++i; + } + return ErrorMessage; + } + + private int[] next(String needle) { + int length = needle.length(), pos = 0, i = 1; + int[] mapper = new int[length]; + while (i < length) { + if (needle.charAt(i) == needle.charAt(pos)) { + ++pos; + mapper[i] = pos; + ++i; + } else { + if (pos > 0) { + --pos; + } else { + mapper[i] = pos; + ++i; + } + } + } + return mapper; + } + + public String strStrEx(String haystack, String needle) { + int[] mapper = nextEx(needle); + int i = 1, pos = 0, haystack_length = haystack.length(), needle_length = needle.length(); + while (i < haystack_length) { + while (haystack.charAt(i) == needle.charAt(pos)) { + ++i; + ++pos; + if (pos == needle_length) { + return haystack.substring(i - needle_length); + } + if (i == haystack_length) { + return ErrorMessage; + } + } + if (pos > 0) { + pos = mapper[pos - 1]; + } else { + pos = 0; + } + ++i; + } + return ""; + } + + private int[] nextEx(String needle) { + int length = needle.length(), i; + int[] mapper = new int[length]; + int[] code = new int[0xff]; + for (i = 0; i < length; ++i) { + char c = needle.charAt(i); + if (code[c] == 0) { + code[c] = i; + mapper[i] = 0; + } else { + mapper[i] = code[c]; + code[c] = i; + } + } + return mapper; + } + + public static void main(String[] args) { + String haystack = "1334123123"; + String needle = "123123"; + String str = new Q34_StrStr().strStr(haystack, needle); + System.out.println(str); + String str2 = new Q34_StrStr().strStrEx(haystack, needle); + System.out.println(str2); + int c = new Q34_StrStr().search(haystack, needle); + System.out.println(c); + + String haystack_test = TestUtil.generateArrayString(65535000, 9); + String needle_test = TestUtil.generateArrayString(500, 9);; + int count = 1; + long span1 = 0, span2 = 0; + while (count-- > 0) { + long l1 = System.currentTimeMillis(); + String t1 = new Q34_StrStr().strStr(haystack, needle); + long l2 = System.currentTimeMillis(); + String t2 = new Q34_StrStr().strStrEx(haystack, needle); + long l3 = System.currentTimeMillis(); + span1 += (l2 - l1); + span2 += (l3 - l2); + } + System.out.println("KMP:" + span1); + System.out.println("ZSQ:" + span2); + } + + //kmp + public int search(String text, String needle) { + int count = 0, pos = 0; + int[] tab = Next(needle); + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == needle.charAt(pos)) { + pos++; + if (pos == needle.length()) { + ++count; + pos = 0; + } + } else { + if (tab[pos] > 0) { + pos = tab[pos - 1]; + } else { + pos = 0; + } + } + } + return count; + } + + public int[] Next(String needle) { + int len = needle.length(), i = 1, pos = 0; + int[] tab = new int[len]; + while (i < len) { + if (needle.charAt(i) == needle.charAt(pos)) { + tab[i] = pos; + pos++; + } else { + if (pos == 0) { + tab[i] = 0; + } else { + pos--; + } + } + ++i; + } + return tab; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q35_InsertInterval.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q35_InsertInterval.java new file mode 100644 index 0000000..c432aac --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q35_InsertInterval.java @@ -0,0 +1,102 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.Iterator; + +public class Q35_InsertInterval { + + public ArrayList insert(ArrayList intervals, Interval newInterval) { + ArrayList solution = new ArrayList<>(); + int i = 0, length = intervals.size(); + for (; i < length; ++i) { + Interval cur = intervals.get(i); + if (newInterval.start > cur.end) { + solution.add(cur); + } else if (newInterval.end < cur.start) { + solution.add(newInterval); + while (i < length) { + solution.add(intervals.get(i++)); + } + } else if (newInterval.end >= cur.start || newInterval.start <= cur.end) { + newInterval.start = Math.min(newInterval.start, cur.start); + newInterval.end = Math.max(newInterval.end, cur.end); + } + + } + if (solution.isEmpty()) { + solution.add(newInterval); + } + return solution; + } + + public class Interval { + + int start; + int end; + + Interval() { + start = 0; + end = 0; + } + + Interval(int s, int e) { + start = s; + end = e; + } + } + + public ArrayList generateSample() { + ArrayList intervals = new ArrayList<>(); + intervals.add(new Interval(1, 3)); + intervals.add(new Interval(6, 7)); + intervals.add(new Interval(10, 12)); + return intervals; + } + + public Interval generateInterval(int s, int e) { + return new Interval(s, e); + } + + public static void main(String[] args) { + Q35_InsertInterval q35 = new Q35_InsertInterval(); + ArrayList intervals = q35.generateSample(); + Interval newInterval = q35.generateInterval(2, 11); + ArrayList solutions = q35.insertMy(intervals, newInterval); + for (Iterator it = solutions.iterator(); it.hasNext();) { + Q35_InsertInterval.Interval interval_item = it.next(); + System.out.println("[" + interval_item.start + "," + interval_item.end + "]"); + + } + } + + //my way + public ArrayList insertMy(ArrayList intervals, Interval newInterval) { + ArrayList solution = new ArrayList<>(); + int len = intervals.size(); + for (int i = 0; i < len; i++) { + Interval cur = intervals.get(i); + if (newInterval.start > cur.end || newInterval.end < cur.start) { + solution.add(cur); + } else if (newInterval.start <= cur.end) { + Interval temp = new Interval(); + temp.start = Math.min(newInterval.start, cur.start); + if (newInterval.end <= cur.end) { + temp.end = Math.max(cur.end, newInterval.end); + } else { + while (++i < len) { + cur = intervals.get(i); + if (newInterval.end <= cur.end) { + temp.end = Math.max(cur.end, newInterval.end); + break; + } + } + } + solution.add(temp); + } + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q36_IntegerToRoman.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q36_IntegerToRoman.java new file mode 100644 index 0000000..efa4995 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q36_IntegerToRoman.java @@ -0,0 +1,141 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q36_IntegerToRoman { + + String[] D1 = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + String[] D10 = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + String[] D100 = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + String[] D1000 = {"M", "MM", "MMM"}; + + public String intToRoman(int num) { + StringBuilder sb = new StringBuilder(); + int i = 4; + while (i > 0) { + int digit = (num / ((int) (Math.pow(10, i) / Math.pow(10, 1)))) % 10; + if (digit > 0) { + switch (i) { + case 4: + sb.append(D1000[digit - 1]); + break; + case 3: + sb.append(D100[digit - 1]); + break; + case 2: + sb.append(D10[digit - 1]); + break; + case 1: + sb.append(D1[digit - 1]); + break; + } + } + --i; + } + return sb.toString(); + } + String[] map = {"I", "V", "X", "L", "C", "D", "M"}; + + public String intToRoman2(int num) { + StringBuilder sb = new StringBuilder(); + int i = 4, count = 0; + while (i > 0) { + int digit = (num / ((int) (Math.pow(10, i) / Math.pow(10, 1)))) % 10; + String s1 = "", s2 = "", s3 = ""; + switch (i) { + case 1: + s1 = "I"; + s2 = "V"; + s3 = "X"; + break; + case 2: + s1 = "X"; + s2 = "L"; + s3 = "C"; + break; + case 3: + s1 = "C"; + s2 = "D"; + s3 = "M"; + break; + case 4: + s1 = "M"; + break; + } + if (digit >= 1 && digit <= 3) { + for (count = 0; count < digit; ++count) { + sb.append(s1); + } + } else if (digit == 4) { + sb.append(s1).append(s2); + } else if (digit >= 5 && digit <= 8) { + sb.append(s2); + for (count = 0; count <= digit - 5; ++count) { + sb.append(s3); + } + } else if (digit == 9) { + sb.append(s1).append(s3); + } + + --i; + } + return sb.toString(); + } + + public static void main(String[] args) { + int num = 3999; + String text = new Q36_IntegerToRoman().intToRoman(num); + System.out.println(text); + String text2 = new Q36_IntegerToRoman().intToRoman2(num); + System.out.println(text2); + String text3 = new Q36_IntegerToRoman().intToRomanMy(num); + System.out.println(text3); + } + + public String intToRomanMy(int num) { + StringBuilder sb = new StringBuilder(); + int digit = 1; + String s1 = "", s2 = "", s3 = ""; + while (num > 0) { + int c = num % 10; + switch (digit) { + case 1: + s1 = "I"; + s2 = "V"; + s3 = "X"; + break; + case 2: + s1 = "X"; + s2 = "L"; + s3 = "C"; + break; + case 3: + s1 = "C"; + s2 = "D"; + s3 = "M"; + break; + case 4: + s1 = "M"; + break; + } + if (c <= 3 && c >= 1) { + for (int i = 0; i < c; i++) { + sb.insert(0, s1); + } + } else if (c == 4) { + sb.insert(0, s1 + s2); + } else if (c >= 5 && c <= 8) { + for (int i = 0; i < c - 5; i++) { + sb.insert(0, s1); + } + sb.insert(0, s2); + } else if (c == 9) { + sb.insert(0, s1 + s3); + } + ++digit; + num /= 10; + } + return sb.toString(); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q37_InterleavingString.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q37_InterleavingString.java new file mode 100644 index 0000000..c1523eb --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q37_InterleavingString.java @@ -0,0 +1,57 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q37_InterleavingString { + + public boolean isInterleave(String s1, String s2, String s3) { + int s1_length = s1.length(), s2_length = s2.length(), s3_length = s3.length(), i = 1, j = 1; + boolean[][] cache = new boolean[s1_length + 1][s2_length + 1]; + cache[0][0] = true; + for (i = 1; i <= s1_length; ++i) { + cache[i][0] = cache[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1); + } + for (j = 1; j <= s2_length; ++j) { + cache[0][j] = cache[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1); + } + for (i = 1; i <= s1_length; ++i) { + for (j = 1; j <= s2_length; ++j) { + cache[i][j] = (cache[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) + || (cache[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1)); + } + } + return cache[s1_length][s2_length]; + } + + public static void main(String[] args) { + String s1 = "ac"; + String s2 = "ca"; + String s3 = "caca"; + boolean result = new Q37_InterleavingString().isInterleaveMy(s1, s2, s3); + System.out.println(result); + } + + //my way + public boolean isInterleaveMy(String s1, String s2, String s3) { + int s1_len = s1.length(), s2_len = s2.length(), s3_len = s3.length(); + if (s1_len + s2_len != s3_len) { + return false; + } + boolean[][] tab = new boolean[1 + s1_len][1 + s2_len]; + tab[0][0] = true; + for (int i = 1; i <= s1_len; i++) { + tab[i][0] = tab[i - 1][0] && (s1.charAt(i - 1) == s3.charAt(i - 1)); + } + for (int i = 1; i <= s2_len; i++) { + tab[0][i] = tab[0][i - 1] && (s2.charAt(i - 1) == s3.charAt(i - 1)); + } + for (int i = 1; i <= s1_len; i++) { + for (int j = 1; j <= s2_len; j++) { + tab[i][j] = tab[i - 1][j] && (s3.charAt(i + j - 1) == s1.charAt(i - 1)) + || tab[i][j - 1] && (s3.charAt(i + j - 1) == s2.charAt(j - 1)); + } + } + return tab[s1_len][s2_len]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q38_JumpGame.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q38_JumpGame.java new file mode 100644 index 0000000..5cbc377 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q38_JumpGame.java @@ -0,0 +1,51 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q38_JumpGame { + + public boolean canJump(int[] A) { + int length = A.length, i = 0, j = 0; + for (; i < length; ++i) { + if (A[i] == 0) { + boolean pass = false; + for (j = i - 1; j >= 0; --j) { + if (A[j] > i - j) { + pass = true; + break; + } + if (!pass) { + return false; + } + } + } + } + return true; + } + + public static void main(String[] args) { + int[] A = {3, 2, 2, 0, 4}; + boolean result = new Q38_JumpGame().canJumpMy(A); + System.out.println(result); + } + + //my way + public boolean canJumpMy(int[] A) { + for (int i = 0; i < A.length; i++) { + if (A[i] == 0) { + boolean pass = false; + for (int j = i - 1; j >= 0; j--) { + if (i - j < A[j]) { + pass = true; + break; + } + } + if (!pass) { + return false; + } + } + } + return true; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q39_JumpGame2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q39_JumpGame2.java new file mode 100644 index 0000000..6bbd58e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q39_JumpGame2.java @@ -0,0 +1,85 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; + +public class Q39_JumpGame2 { + + public int jumpEx(int[] A) { + int length = A.length; + int[] cache = new int[length]; + int i = 1, j = 0; + for (; i < length; ++i) { + cache[i] = Integer.MAX_VALUE; + } + cache[0] = 0; + for (i = 0; i < length; ++i) { + int pre_dis = cache[i]; + int dis = A[i]; + for (j = 1; j <= dis; ++j) { + if (i + j < length) { + cache[i + j] = Math.min(cache[i + j], 1 + pre_dis); + } + } + } + return cache[length - 1]; + } + + public int jump(int[] A) { + int length = A.length, i = 1, j = 0; + int[] MinJump = new int[length]; + MinJump[0] = 0; + int Min = Integer.MAX_VALUE; + for (; i < length; ++i) { + Min = Integer.MAX_VALUE; + for (j = 0; j < i; ++j) { + if (MinJump[j] >= Min) { + continue; + } + if (A[j] >= i - j) { + Min = Math.min(Min, MinJump[j] + 1); + } + } + MinJump[i] = Min; + } + return MinJump[length - 1]; + } + + public static void main(String[] args) { + int[] A = {1, 5, 4, 3, 1, 2, 0, 1}; + int step = new Q39_JumpGame2().jumpMy(A); + System.out.println(step); + int step2 = new Q39_JumpGame2().jumpEx(A); + System.out.println(step2); + + + int[] testA = TestUtil.generateArray(999, 50, false); + long l1 = System.currentTimeMillis(); + int stepa = new Q39_JumpGame2().jumpMy(testA); + long l2 = System.currentTimeMillis(); + int stepb = new Q39_JumpGame2().jumpEx(testA); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(stepa + " Cost " + span1); + System.out.println(stepb + " Cost " + span2); + } + + //most correct one + public int jumpMy(int[] A) { + int[] tab = new int[A.length]; + for (int i = 0; i < A.length; i++) { + tab[i] = Integer.MAX_VALUE; + } + for (int i = 0; i < A.length; i++) { + for (int j = i; j <= i + A[i]; j++) { + tab[j] = Math.min(tab[j], 1 + i); + if (j == A.length - 1) { + return tab[j]; + } + } + } + return tab[A.length - 1]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q3_4Sum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q3_4Sum.java new file mode 100644 index 0000000..bfa6e8c --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q3_4Sum.java @@ -0,0 +1,160 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.HashSet; + +public class Q3_4Sum { + + public ArrayList> fourSum(int[] num, int target) { + java.util.Arrays.sort(num); + HashSet cache = new HashSet<>(); + ArrayList> solutions = new ArrayList<>(); + int i = 0, j = 0, length = num.length; + for (; i < length - 4; i++) { + for (j = i + 1; j < length - 3; j++) { + int s = j + 1; + int e = length - 1; + while (s < e) { + int curren_sum = num[i] + num[j] + num[s] + num[e]; + String key = String.valueOf(num[e]) + String.valueOf(num[s]) + String.valueOf(num[j]) + String.valueOf(num[i]); + if (cache.contains(key)) { + --e; + ++s; + } else if (curren_sum > target) { + --e; + } else if (curren_sum < target) { + ++s; + } else { + ArrayList solution = new ArrayList<>(); + solution.add(num[e]); + solution.add(num[s]); + solution.add(num[j]); + solution.add(num[i]); + solutions.add(solution); + cache.add(key); + --e; + ++s; + } + } + } + } + + return solutions; + } + + /* + public ArrayList> fourSumEx(int[] num, int target) { + java.util.Arrays.sort(num); + ArrayList> solutions = new ArrayList<>(); + int length = num.length, l = 0, r = length - 1, ml = l + 1, mr = r - 1; + while (r - l >= 2) { + int current_sum = num[l] + num[r]; + if (current_sum >= target) { + ml = l + 1; + } else if (current_sum < target) { + ml = r - 1; + } + current_sum += num[ml]; + if (current_sum >= target) { + mr = l + 1; + if (mr == ml) { + mr = ml + 1; + } + } else if (current_sum < target) { + mr = r - 1; + if (mr == ml) { + mr = ml - 1; + } + } + current_sum += num[mr]; + while (ml < mr) { + if (current_sum == target) { + ArrayList solution = new ArrayList<>(); + solution.add(num[r]); + solution.add(num[mr]); + solution.add(num[ml]); + solution.add(num[l]); + solutions.add(solution); + --mr; + ++ml; + } else if (current_sum > target) { + --mr; + } else { + ++ml; + } + } + --r; + ++l; + } + return solutions; + + } + */ + //my way + public ArrayList> fourSumEx(int[] num, int target) { + java.util.Arrays.sort(num); + ArrayList> solutions = new ArrayList<>(); + HashSet cache = new HashSet<>(); + int length = num.length, i, j, s, e; + for (i = 0; i < length - 4; i++) { + for (j = i + 1; j < length - 3; j++) { + s = j + 1; + e = length - 1; + while (s < e) { + int sum = num[i] + num[j] + num[s] + num[e]; + if (sum == target) { + String key = String.valueOf(num[i]) + String.valueOf(num[j]) + String.valueOf(num[s]) + String.valueOf(num[e]); + if (cache.contains(key)) { + continue; + }else{ + cache.add(key); + ArrayList solution = new ArrayList<>(); + solution.add(num[i]); + solution.add(num[j]); + solution.add(num[s]); + solution.add(num[e]); + solutions.add(solution);} + ++s; + --e; + } else if (sum < target) { + ++s; + } else if (sum > target) { + --e; + } + } + } + } + return solutions; + } + + public static void main(String[] args) { + int[] num = {1, 0, -1, 0, -2, 2}; + ArrayList> solutions = new Q3_4Sum().fourSum(num, 0); + for (Iterator> it = solutions.iterator(); it.hasNext();) { + ArrayList arrayList = it.next(); + for (Iterator it1 = arrayList.iterator(); it1.hasNext();) { + System.out.print(it1.next()); + System.out.print(" "); + } + System.out.println(); + } + + //test + int[] arr = Util.TestUtil.generateArray(30); + long t1 = System.currentTimeMillis(); + ArrayList> solutions1 = new Q3_4Sum().fourSum(arr, 0); + long t2 = System.currentTimeMillis(); + ArrayList> solutions2 = new Q3_4Sum().fourSumEx(arr, 0); + long t3 = System.currentTimeMillis(); + long span1 = t2 - t1; + long span2 = t3 - t2; + System.out.println(solutions1.size() + " Cost " + span1); + System.out.println(solutions2.size() + " Cost " + span2); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q40_LargestRectangleInHistogram.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q40_LargestRectangleInHistogram.java new file mode 100644 index 0000000..20762be --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q40_LargestRectangleInHistogram.java @@ -0,0 +1,115 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; +import java.util.Stack; + +public class Q40_LargestRectangleInHistogram { + + //wrong + public int largestRectangleAreaEx(int[] height) { + int length = height.length, MaxArea = Integer.MIN_VALUE, s = 0, e = length - 1; + while (s < e) { + int cur = Math.min(height[s], height[e]) * (e - s + 1); + MaxArea = Math.max(cur, MaxArea); + if (height[s] >= height[e]) { + while (height[e] >= height[--e]) { + } + } else { + while (height[s] >= height[++s]) { + } + } + } + return MaxArea; + } + + public int largestRectangleArea(int[] height) { + int length = height.length, MaxArea = Integer.MIN_VALUE, ind = 0; + Stack height_stack = new Stack<>(); + Stack index_stack = new Stack<>(); + height_stack.push(height[0]); + index_stack.push(0); + int i = 1; + for (; i < length; ++i) { + if (height[i] > height_stack.peek()) { + height_stack.push(height[i]); + index_stack.push(i); + } else if (height[i] == height_stack.peek()) { + continue; + } else { + do { + int h = height_stack.pop(); + ind = index_stack.pop(); + int area = h * (i - ind); + MaxArea = Math.max(area, MaxArea); + } while (!height_stack.isEmpty() && height[i] < height_stack.peek()); + height_stack.push(height[i]); + index_stack.push(ind); + } + } + while (!height_stack.isEmpty()) { + int h = height_stack.pop(); + ind = index_stack.pop(); + int area = h * (length - ind); + MaxArea = Math.max(area, MaxArea); + } + return MaxArea; + } + + public static void main(String[] args) { + int[] height = {2, 1, 5, 6, 2,2,2, 3}; + int area = new Q40_LargestRectangleInHistogram().largestRectangleAreaMy(height); + System.out.println(area); + int area2 = new Q40_LargestRectangleInHistogram().largestRectangleAreaEx(height);//wrong way + System.out.println(area2); + + int[] height_test = {2, 5, 4, 1};//TestUtil.generateArray(9, 9, false); + long l1 = System.currentTimeMillis(); + int area_t1 = new Q40_LargestRectangleInHistogram().largestRectangleArea(height_test); + long l2 = System.currentTimeMillis(); + int area_t2 = new Q40_LargestRectangleInHistogram().largestRectangleAreaEx(height_test); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(area_t1 + " Cost " + span1); + System.out.println(area_t2 + " Cost " + span2); + } + + //my way correct + public int largestRectangleAreaMy(int[] height) { + Stack stack = new Stack<>(); + int len = height.length, i = 0; + int max = 0; + while (i < len) { + if (stack.isEmpty() || height[i] > stack.peek()._height) { + stack.push(new Wrapper(height[i], i)); + } else if (stack.peek()._height > height[i]) { + int prev = 0; + while (!stack.isEmpty() && stack.peek()._height > height[i]) { + Wrapper wr = stack.pop(); + prev = wr._index; + max = Math.max(max, (i - prev) * wr._height); + } + stack.push(new Wrapper(height[i], prev)); + } + ++i; + } + while (!stack.isEmpty()) { + Wrapper wr = stack.pop(); + max = Math.max(max, (i - wr._index) * wr._height); + } + return max; + } + + class Wrapper { + + int _height; + int _index; + + public Wrapper(int height, int index) { + this._height = height; + this._index = index; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q41_LengthOfLastWord.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q41_LengthOfLastWord.java new file mode 100644 index 0000000..a7ad588 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q41_LengthOfLastWord.java @@ -0,0 +1,45 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 20, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q41_LengthOfLastWord { + + public int lengthOfLastWord(String s) { + int length = s.length(), i = length - 1, e = length - 1; + while (i >= 0) { + if (s.charAt(i) == ' ') { + if (e - i == 0) { + e = i - 1; + } else { + return e - i; + } + } + --i; + } + return -1; + } + + public static void main(String[] args) { + String text = "hello world ha"; + int l = new Q41_LengthOfLastWord().lengthOfLastWordMy(text); + System.out.println(l); + } + + //my way + public int lengthOfLastWordMy(String s) { + int len = s.length(), i; + boolean start = false; + for (i = len - 1; i >= 0; i--) { + if (s.charAt(i) != ' ') { + start = true; + } + if (start) { + if (s.charAt(i) == ' ') { + return len - i - 1; + } + } + } + return -1; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q42_LetterCombinationPhoneNum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q42_LetterCombinationPhoneNum.java new file mode 100644 index 0000000..0547c66 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q42_LetterCombinationPhoneNum.java @@ -0,0 +1,130 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +public class Q42_LetterCombinationPhoneNum { + + public ArrayList letterCombinationsEx(String digits) { + HashMap mapper = new HashMap<>(); + mapper.put(0, new Character[]{'@'}); + mapper.put(1, new Character[]{'$'}); + mapper.put(2, new Character[]{'a', 'b', 'c'}); + mapper.put(3, new Character[]{'d', 'e', 'f'}); + mapper.put(4, new Character[]{'g', 'h', 'i'}); + mapper.put(5, new Character[]{'j', 'k', 'l'}); + mapper.put(6, new Character[]{'m', 'n', 'o'}); + mapper.put(7, new Character[]{'p', 'q', 'r', 's'}); + mapper.put(8, new Character[]{'t', 'u', 'v'}); + mapper.put(9, new Character[]{'w', 'x', 'y', 'z'}); + int length = digits.length(); + ArrayList solution = new ArrayList<>(); + letterCombinationsHelper(digits, 0, length, "", mapper, solution); + return solution; + } + + public ArrayList letterCombinations(String digits) { + HashMap mapper = new HashMap<>(); + mapper.put(0, new char[]{'@'}); + mapper.put(1, new char[]{'$'}); + mapper.put(2, new char[]{'a', 'b', 'c'}); + mapper.put(3, new char[]{'d', 'e', 'f'}); + mapper.put(4, new char[]{'g', 'h', 'i'}); + mapper.put(5, new char[]{'j', 'k', 'l'}); + mapper.put(6, new char[]{'m', 'n', 'o'}); + mapper.put(7, new char[]{'p', 'q', 'r', 's'}); + mapper.put(8, new char[]{'t', 'u', 'v'}); + mapper.put(9, new char[]{'w', 'x', 'y', 'z'}); + ArrayList[] solutions = new ArrayList[2]; + solutions[0] = new ArrayList<>(); + solutions[1] = new ArrayList<>(); + for (char ch : mapper.get(digits.charAt(0) - '0')) { + solutions[0].add(String.valueOf(ch)); + } + int i = 1, length = digits.length(); + for (; i < length; ++i) { + for (String pre_text : solutions[(i - 1) % 2]) { + for (char ch : mapper.get(digits.charAt(i) - '0')) { + solutions[i % 2].add(pre_text + String.valueOf(ch)); + } + } + solutions[(i - 1) % 2].clear(); + } + return solutions[(i - 1) % 2]; + } + + private void letterCombinationsHelper(String digit, int i, int length, String cur, + HashMap mapper, ArrayList solution) { + if (i == length) { + solution.add(cur); + return; + } + int num = digit.charAt(i) - '0'; + Character[] arr = mapper.get(num); + for (Character ch : arr) { + letterCombinationsHelper(digit, i + 1, length, cur + ch, mapper, solution); + } + } + + public static void main(String[] args) { + String digits = "23"; + ArrayList solution = new Q42_LetterCombinationPhoneNum().letterCombinationsMy(digits); + for (Iterator it = solution.iterator(); it.hasNext();) { + String string = it.next(); + System.out.println(string); + } + + String digits_test = TestUtil.generateArrayString(9, 100); + long l1 = System.currentTimeMillis(); + ArrayList solution1 = new Q42_LetterCombinationPhoneNum().letterCombinations(digits_test); + long l2 = System.currentTimeMillis(); + ArrayList solution2 = new Q42_LetterCombinationPhoneNum().letterCombinationsEx(digits_test); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(solution1.size() + " Cost " + span1); + System.out.println(solution2.size() + " Cost " + span2); + } + + //my way + public ArrayList letterCombinationsMy(String digits) { + ArrayList[] solutions = new ArrayList[2]; + solutions[0] = new ArrayList<>(); + solutions[1] = new ArrayList<>(); + HashMap mapper = new HashMap<>(); + mapper.put(0, new Character[]{'@'}); + mapper.put(1, new Character[]{'$'}); + mapper.put(2, new Character[]{'a', 'b', 'c'}); + mapper.put(3, new Character[]{'d', 'e', 'f'}); + mapper.put(4, new Character[]{'g', 'h', 'i'}); + mapper.put(5, new Character[]{'j', 'k', 'l'}); + mapper.put(6, new Character[]{'m', 'n', 'o'}); + mapper.put(7, new Character[]{'p', 'q', 'r', 's'}); + mapper.put(8, new Character[]{'t', 'u', 'v'}); + mapper.put(9, new Character[]{'w', 'x', 'y', 'z'}); + int len = digits.length(), i; + for (i = 0; i < len; i++) { + ArrayList cur = solutions[i % 2]; + ArrayList pre = solutions[(1 + i) % 2]; + cur.clear(); + char ch = digits.charAt(i); + Character[] char_list = mapper.get(ch - '0'); + if (pre.isEmpty()) { + for (Character character : char_list) { + cur.add(String.valueOf(character)); + } + } else { + for (String string : pre) { + for (Character character : char_list) { + cur.add(String.valueOf(string + character)); + } + } + } + } + return solutions[(i + 1) % 2]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q43_LongestCommonPrefix.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q43_LongestCommonPrefix.java new file mode 100644 index 0000000..cb5f7cf --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q43_LongestCommonPrefix.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q43_LongestCommonPrefix { + + public String longestCommonPrefix(String[] strs) { + StringBuilder sb = new StringBuilder(); + int index = 0; + boolean cont = true; + while (cont) { + for (String item : strs) { + if (index >= item.length() || strs[0].charAt(index) != item.charAt(index)) { + cont = false; + break; + } + } + if (cont) { + sb.append(strs[0].charAt(index)); + ++index; + } + } + return sb.toString(); + } + + public static void main(String[] args) { + String[] strs = {"abccce", "abccw", "abccr", "abcss", "abcee"}; + String prefix = new Q43_LongestCommonPrefix().longestCommonPrefixMy(strs); + System.out.println(prefix); + } + + //my way + public String longestCommonPrefixMy(String[] strs) { + int b = -1; + String std = strs[0]; + boolean cont = true; + while (cont) { + ++b; + for (int i = 1; i < strs.length; i++) { + if (strs[i].charAt(b) != std.charAt(b)) { + cont = false; + --b; + break; + } + } + } + return strs[0].substring(0, b + 1); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q44_LongestPalindromicSub.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q44_LongestPalindromicSub.java new file mode 100644 index 0000000..5d4ba23 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q44_LongestPalindromicSub.java @@ -0,0 +1,75 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q44_LongestPalindromicSub { + + public String longestPalindromeEx(String s) { + int length = s.length(), i = 0; + int palindrome_length = 0; + String palindrome = ""; + for (; i < length; ++i) { + if (i + 1 < length && s.charAt(i) == s.charAt(1 + i)) { + int cur_length = longestPalindromeExHelper(i, 1 + i, s, length); + if (cur_length > palindrome_length) { + palindrome = s.substring(i - cur_length / 2 + 1, i + 1 + cur_length / 2 - 1 + 1); + palindrome_length = cur_length; + } + } + if (i + 2 < length && s.charAt(i) == s.charAt(2 + i)) { + int cur_length = longestPalindromeExHelper(i, 2 + i, s, length); + if (cur_length > palindrome_length) { + palindrome = s.substring(i - cur_length / 2 + 1, i + 2 + cur_length / 2 - 1 + 1); + palindrome_length = cur_length; + } + } + } + return palindrome; + } + + private int longestPalindromeExHelper(int a, int b, String s, int length) { + do { + --a; + ++b; + } while (a >= 0 && b < length && s.charAt(a) == s.charAt(b)); + return b - a - 1; + } + + public static void main(String[] args) { + String s = "ABCCSTSABASS"; + String palindrome = new Q44_LongestPalindromicSub().longestPalindromeMy(s); + System.out.println(palindrome); + } + + public String longestPalindromeMy(String s) { + int len = s.length(), l = 0, max = 0; + for (int i = 0; i < len; i++) { + if (i + 2 < len && s.charAt(i) == s.charAt(i + 2)) { + int radius = longestPalindromeMyHelper(s, i, i + 2); + if (radius * 2 + 1 > max) { + max = radius * 2 + 1; + l = i - radius + 1; + } + } + if (i + 1 < len && s.charAt(i) == s.charAt(i + 1)) { + int radius = longestPalindromeMyHelper(s, i, i + 1); + if (radius * 2 > max) { + max = radius * 2; + l = i - radius + 1; + } + } + } + return s.substring(l, l + max); + } + + private int longestPalindromeMyHelper(String s, int l, int r) { + int len = s.length(); + int pre_l = l; + do { + --l; + ++r; + } while (l >= 0 && r < len && s.charAt(l) == s.charAt(r)); + return pre_l - (l + 1) + 1; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q45_LongestSubWithoutRepeat.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q45_LongestSubWithoutRepeat.java new file mode 100644 index 0000000..5cd5d7f --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q45_LongestSubWithoutRepeat.java @@ -0,0 +1,98 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.HashMap; + +public class Q45_LongestSubWithoutRepeat { + + public int lengthOfLongestSubstring(String s) { + int length = s.length(), a = 0, b = 0, MaxLeng = 0; + boolean[] record = new boolean[0xff]; + while (b < length) { + if (record[s.charAt(b)]) { + MaxLeng = Math.max(MaxLeng, b - a); + while (s.charAt(a) != s.charAt(b)) { + record[s.charAt(++a)] = false; + ++a; + } + ++a; + } else { + record[s.charAt(b)] = true; + } + ++b; + } + return MaxLeng; + } + + public static void main(String[] args) { + String s = "abcabcbbe"; + int c = new Q45_LongestSubWithoutRepeat().lengthOfLongestSubstringMy(s); + System.out.println(c); + int c2 = new Q45_LongestSubWithoutRepeat().lengthOfLongestSubstring(s); + System.out.println(c2); + } + + public int lengthOfLongestSubstringMy(String s) { + int len = s.length(), l = 0, max = 0, cur = 0; + HashMap mapper = new HashMap<>(); + for (int i = 0; i < len; i++) { + char ch = s.charAt(i); + if (mapper.containsKey(ch)) { + max = Math.max(max, cur); + int pos = mapper.get(ch); + for (int j = l; j <= pos; j++) { + --cur; + mapper.remove(s.charAt(j)); + } + ++cur; + mapper.put(ch, i); + l = pos + 1; + } else { + mapper.put(ch, i); + ++cur; + } + } + max = Math.max(max, cur); + return max; + } + + public int lengthOfLongestSubstringSample(String s) { + //I use hashmap because the string may contain unicode chars that are 0~65535 + + //str contains the index of chars that are in the current substring + //a char is in the substring if str.constainsKey + HashMap str = new HashMap(); + int len = 0, max = 0; + int startIndex = 0; + for (int i = 0; i < s.length(); i++) { + if (!str.containsKey(s.charAt(i))) { + str.put(s.charAt(i), i); + len++; + } else { //found a duplicate + if (max < len) { + max = len; //update the max + } + + //or you can continue from the char after the first duplicate + int dupIndex = str.get(s.charAt(i)); + for (int j = dupIndex; j >= startIndex; j--) { + str.remove(s.charAt(j)); + len--; + } + //add the second duplicate to map (it is not a duplicate anymore) + str.put(s.charAt(i), i); + len++; + startIndex = dupIndex + 1; + } + } + + //len is length of the last substring + if (len > max) { + max = len; + } + + return max; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q46_LongestValidParentheses.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q46_LongestValidParentheses.java new file mode 100644 index 0000000..10a3c31 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q46_LongestValidParentheses.java @@ -0,0 +1,65 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.Stack; + +public class Q46_LongestValidParentheses { + + public int longestValidParentheses(String s) { + int length = s.length(), i, max = 0, start = length, cur = 0; + Stack st = new Stack<>(); + for (i = 0; i < length; ++i) { + char ch = s.charAt(i); + if (ch == '(') { + st.push(i); + } else if (ch == ')') { + if (st.isEmpty()) { + start = length; + } else { + start = Math.min(start, st.pop()); + if (st.isEmpty()) { + cur = i - start + 1; + max = Math.max(cur, max); + } else { + cur = i - st.peek(); + max = Math.max(cur, max); + } + } + } + } + return max; + } + + public static void main(String[] args) { + String s = "()()(()"; + int max = new Q46_LongestValidParentheses().longestValidParenthesesMy(s); + System.out.println(max); + } + + //my way + public int longestValidParenthesesMy(String s) { + int len = s.length(), max = 0, i = 0, left = 0; + Stack stack = new Stack<>(); + while (i < len) { + char ch = s.charAt(i); + if (ch == '(') { + stack.push(i); + } else if (ch == ')') { + if (!stack.isEmpty()) { + int pos = stack.pop(); + if (stack.isEmpty()) { + max = Math.max(max, i - left + 1); + } else { + max = Math.max(max, i - (stack.peek() + 1) + 1); + } + } else { + left = i + 1; + } + } + ++i; + } + return max; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q47_MaxRectangle.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q47_MaxRectangle.java new file mode 100644 index 0000000..65d3590 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q47_MaxRectangle.java @@ -0,0 +1,86 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q47_MaxRectangle { + + public int maximalRectangle(char[][] matrix) { + int i = 0, j = 0, height = matrix.length, width = matrix[0].length, max = 0; + int[][] dp = new int[height][width]; + for (i = 0; i < height; ++i) { + for (j = 0; j < width; ++j) { + if (matrix[i][j] == '1') { + if (j >= 1) { + dp[i][j] = dp[i][j - 1] + 1; + } else { + dp[i][j] = 1; + } + max = Math.max(dp[i][j], max); + } else { + dp[i][j] = 0; + } + } + } + for (i = 0; i < height; ++i) { + for (j = 0; j < width; ++j) { + int k = i; + int min = dp[k][j]; + while (k >= 0 && dp[k][j] != 0) { + min = Math.min(dp[k][j], min); + int h = i - k + 1; + int area = min * h; + max = Math.max(max, area); + --k; + } + } + } + return max; + } + + public static void main(String[] args) { + char[][] matrix = { + {'1', '1', '1', '0'}, + {'1', '1', '1', '0'}, + {'0', '1', '1', '1'}, + {'0', '1', '1', '1'} + }; + int area = new Q47_MaxRectangle().maximalRectangle(matrix); + System.out.println(area); + } + + //my way + //wrong!!! + public int maximalRectangleMy(char[][] matrix) { + int height = matrix.length, width = matrix[0].length, col, row, max = 0; + int[][] tab = new int[height][width]; + for (col = 0; col < height; col++) { + for (row = 0; row < width; row++) { + if (matrix[col][row] == '1') { + if (row >= 1) { + tab[col][row] = tab[col][row - 1] + 1; + } else { + tab[col][row] = 1; + } + } else if (matrix[col][row] == '0') { + tab[col][row] = 0; + } + } + } + for (col = 0; col < height; col++) { + for (row = 0; row < width; row++) { + if (matrix[col][row] == '1') { + if (col >= 1) { + tab[col][row] = tab[col - 1][row] + tab[col][row]; + } + } + } + } + for (col = 0; col < height; col++) { + for (row = 0; row < width; row++) { + max = Math.max(max, tab[col][row]); + } + } + return max; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q48_MaxDepthOfBinaryTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q48_MaxDepthOfBinaryTree.java new file mode 100644 index 0000000..66e04d7 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q48_MaxDepthOfBinaryTree.java @@ -0,0 +1,25 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q48_MaxDepthOfBinaryTree { + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + int depth = new Q48_MaxDepthOfBinaryTree().maxDepthMy(root); + System.out.println(depth); + } + + //my way + public int maxDepthMy(BinaryTreeNode root) { + if (root == null) { + return 0; + } + int l = maxDepthMy(root.Left); + int r = maxDepthMy(root.Right); + return Math.max(l, r) + 1; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q49_MaxSubarray.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q49_MaxSubarray.java new file mode 100644 index 0000000..d444817 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q49_MaxSubarray.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 21, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q49_MaxSubarray { + + public int maxSubArray(int[] A) { + int i, length = A.length, cur = 0; + int max = Integer.MIN_VALUE; + for (i = 0; i < length; ++i) { + cur += A[i]; + if (cur < 0) { + max = Math.max(max, cur - A[i]); + cur = 0; + } + } + max = Math.max(max, cur); + if (max <= 0) { + max = Integer.MIN_VALUE; + for (i = 0; i < length; ++i) { + max = Math.max(max, A[i]); + } + } + return max; + } + + public static void main(String[] args) { + int[] A = {1, 2, 3, -2}; + int max = new Q49_MaxSubarray().maxSubArrayMy(A); + System.out.println(max); + } + + //my way + public int maxSubArrayMy(int[] A) { + int max = 0, len = A.length, count = 0;; + for (int i = 0; i < len; i++) { + count += A[i]; + if (count < 0) { + count = 0; + } else { + max = Math.max(max, count); + } + } + return max; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q4_AddBinary.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q4_AddBinary.java new file mode 100644 index 0000000..e59cf69 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q4_AddBinary.java @@ -0,0 +1,72 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q4_AddBinary { + + public String addBinary(String a, String b) { + StringBuilder sb = new StringBuilder(); + int a_length = a.length(), b_length = b.length(), i = 0; + int shorter_length = Math.min(a_length, b_length), longer_length = Math.max(a_length, b_length); + String longer = a_length >= b_length ? a : b; + boolean carry = false; + for (; i < shorter_length; i++) { + if (!carry) { + if (a.charAt(i) == '1' && b.charAt(i) == '1') { + sb.insert(0, '0'); + carry = true; + } else if (a.charAt(i) == '0' && b.charAt(i) == '0') { + sb.insert(0, '0'); + carry = false; + } else { + sb.insert(0, '1'); + carry = false; + } + } else { + if (a.charAt(i) == '1' && b.charAt(i) == '1') { + sb.insert(0, '1'); + carry = true; + } else if (a.charAt(i) == '0' && b.charAt(i) == '0') { + sb.insert(0, '1'); + carry = false; + } else { + sb.insert(0, '0'); + carry = true; + } + } + } + for (; i < longer_length; i++) { + if (!carry) { + if (longer.charAt(i) == '1') { + sb.insert(0, '1'); + } else { + sb.insert(0, '0'); + } + } else { + if (longer.charAt(i) == '1') { + sb.insert(0, '0'); + carry = true; + } else { + sb.insert(0, '1'); + carry = false; + } + } + } + if (carry) { + sb.insert(0, '1'); + } + return sb.toString(); + } + + public String addBinarySimple(String a, String b) { + return Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2)); + } + + + public static void main(String[] args) { + String solution = new Q4_AddBinary().addBinary("11", "1"); + System.out.println(solution); + System.out.println(new Q4_AddBinary().addBinarySimple("11", "1")); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q50_MedianOfTwoSortedArray.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q50_MedianOfTwoSortedArray.java new file mode 100644 index 0000000..889577d --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q50_MedianOfTwoSortedArray.java @@ -0,0 +1,176 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q50_MedianOfTwoSortedArray { + + public double findMedianSortedArrays(int A[], int B[]) { + int a_length = A.length, b_length = B.length; + int i = 0, j = 0, count = 0; + int mid1 = (a_length + b_length) / 2 - ((a_length + b_length) % 2 == 0 ? 1 : 0); + int mid2 = (a_length + b_length) / 2; + double median1 = 0, median2 = 0; + while (count <= mid2) { + if (i >= a_length) { + if (count == mid1) { + median1 = B[j]; + } + if (count == mid2) { + median2 = B[j]; + } + ++j; + ++count; + continue; + } + if (j >= b_length) { + if (count == mid1) { + median1 = A[i]; + } + if (count == mid2) { + median2 = A[i]; + } + ++i; + ++count; + continue; + } + if (A[i] >= B[j]) { + if (count == mid1) { + median1 = B[j]; + } + if (count == mid2) { + median2 = B[j]; + } + ++j; + } else { + if (count == mid1) { + median1 = A[i]; + } + if (count == mid2) { + median2 = A[i]; + } + ++i; + } + ++count; + } + return (median1 + median2) / 2; + } + + public double findMedianSortedArraysLog(int A[], int B[]) { + int a_length = A.length, b_length = B.length; + int length = a_length + b_length; + if (length % 2 == 0) { + return findMedianSortedArraysHelper(A, 0, a_length, B, 0, b_length, length / 2) / 2 + + findMedianSortedArraysHelper(A, 0, a_length, B, 0, b_length, length / 2 + 1) / 2; + } else { + return findMedianSortedArraysHelper(A, 0, a_length, B, 0, b_length, length / 2 + 1); + } + } + + public double findMedianSortedArraysHelper(int A[], int aoffset, int a_length, int B[], int boffset, int b_length, int k) { + if (a_length > b_length) { + return findMedianSortedArraysHelper(B, boffset, b_length, A, aoffset, a_length, k); + } + if (a_length == 0) { + return B[k - 1]; + } + if (k == 1) { + return Math.min(A[aoffset], B[boffset]); + } + int pa = Math.min(a_length, k / 2); + int pb = k - pa; + + if (A[aoffset + pa - 1] <= B[boffset + pb - 1]) { + return findMedianSortedArraysHelper(A, aoffset + pa, a_length - pa, B, boffset, b_length, k - pa); + } else { + return findMedianSortedArraysHelper(A, aoffset, a_length, B, boffset + pb, b_length - pb, k - pb); + } + + } + + public static void main(String[] args) { + int A[] = {1, 3, 5}; + int B[] = {2, 4, 6, 7}; + double median = new Q50_MedianOfTwoSortedArray().findMedianSortedArraysMy(A, B); + System.out.println(median); + double median2 = new Q50_MedianOfTwoSortedArray().findMedianSortedArraysLog(A, B); + System.out.println(median2); + } + + public double findMedianSortedArraysMy(int A[], int B[]) { + int a_len = A.length, b_len = B.length, len = a_len + b_len, a_ind = 0, b_ind = 0; + int mid1, mid2, median1 = 0, median2 = 0; + if (len % 2 == 0) { + mid1 = len / 2 - 1; + mid2 = len / 2; + while (a_ind + b_ind < len) { + if (a_ind == a_len) { + ++b_ind; + if (a_ind + b_ind == mid1) { + median1 = A[b_ind]; + } else if (a_ind + b_ind == mid2) { + median2 = A[b_ind]; + } + continue; + } + if (b_ind == b_len) { + ++a_ind; + if (a_ind + b_ind == mid1) { + median1 = A[a_ind]; + } else if (a_ind + b_ind == mid2) { + median2 = A[a_ind]; + } + continue; + } + + if (A[a_ind] <= B[b_ind]) { + if (a_ind + b_ind == mid1) { + median1 = A[a_ind]; + } else if (a_ind + b_ind == mid2) { + median2 = A[a_ind]; + } + ++a_ind; + } else { + if (a_ind + b_ind == mid1) { + median1 = B[b_ind]; + } else if (a_ind + b_ind == mid2) { + median2 = B[b_ind]; + } + ++b_ind; + } + } + return (float) median1 / 2 + (float) median2 / 2; + } else { + mid1 = len / 2 ; + while (a_ind + b_ind < len) { + if (a_ind == a_len) { + ++b_ind; + if (a_ind + b_ind == mid1) { + median1 = A[b_ind]; + } + continue; + } + if (b_ind == b_len) { + ++a_ind; + if (a_ind + b_ind == mid1) { + median1 = A[a_ind]; + } + continue; + } + + if (A[a_ind] <= B[b_ind]) { + if (a_ind + b_ind == mid1) { + median1 = A[a_ind]; + } + ++a_ind; + } else { + if (a_ind + b_ind == mid1) { + median1 = B[b_ind]; + } + ++b_ind; + } + } + return (float) median1; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q51_MergeIntervals.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q51_MergeIntervals.java new file mode 100644 index 0000000..d175ecc --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q51_MergeIntervals.java @@ -0,0 +1,88 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.Iterator; + +public class Q51_MergeIntervals { + + public ArrayList merge(ArrayList intervals) { + ArrayList solution = new ArrayList<>(); + int i, length = intervals.size(); + Interval pre = intervals.get(0); + for (i = 1; i < length; ++i) { + Interval cur = intervals.get(i); + if (cur.start > pre.end) { + solution.add(pre); + pre = cur; + } else { + pre.start = Math.min(cur.start, pre.start); + pre.end = Math.max(cur.end, pre.end); + } + } + solution.add(pre); + return solution; + } + + public class Interval { + + int start; + int end; + + Interval() { + start = 0; + end = 0; + } + + Interval(int s, int e) { + start = s; + end = e; + } + } + + public static void main(String[] args) { + Q51_MergeIntervals.Interval i1 = new Q51_MergeIntervals().new Interval(1, 3); + Q51_MergeIntervals.Interval i2 = new Q51_MergeIntervals().new Interval(2, 6); + Q51_MergeIntervals.Interval i3 = new Q51_MergeIntervals().new Interval(8, 10); + Q51_MergeIntervals.Interval i4 = new Q51_MergeIntervals().new Interval(15, 18); + ArrayList old = new ArrayList<>(); + old.add(i1); + old.add(i2); + old.add(i3); + old.add(i4); + ArrayList solution = new Q51_MergeIntervals().mergeMy(old); + for (Iterator it = solution.iterator(); it.hasNext();) { + Q51_MergeIntervals.Interval interval = it.next(); + System.out.println("[" + interval.start + "," + interval.end + "]"); + } + } + + //my way + public ArrayList mergeMy(ArrayList intervals) { + ArrayList solution = new ArrayList<>(); + int i = 1, len = intervals.size(); + for (; i < len; i++) { + if (intervals.get(i).start <= intervals.get(i - 1).end) { + Interval temp = new Interval(); + temp.start = Math.min(intervals.get(i).start, intervals.get(i - 1).start); + temp.end = Math.max(intervals.get(i).end, intervals.get(i - 1).end); + while (i++ < len) { + if (intervals.get(i).start <= intervals.get(i - 1).end) { + temp.end = Math.max(intervals.get(i).end, intervals.get(i - 1).end); + } else { + break; + } + } + solution.add(temp); + } else { + solution.add(intervals.get(i - 1)); + if (i == len - 1) { + solution.add(intervals.get(i)); + } + } + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q52_MergeKSortedList.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q52_MergeKSortedList.java new file mode 100644 index 0000000..06fd532 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q52_MergeKSortedList.java @@ -0,0 +1,106 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; +import java.util.ArrayList; + +public class Q52_MergeKSortedList { + + public LinkedListNode mergeKLists(ArrayList> lists) { + LinkedListNode pre = null, head = null; + while (true) { + LinkedListNode MinNode = null; + int min_index = 0, i, length = lists.size(); + + boolean exit = true; + for (LinkedListNode node : lists) { + if (node != null) { + exit = false; + } + } + if (exit) { + break; + } + + for (i = 0; i < length; ++i) { + LinkedListNode node = lists.get(i); + if (node != null) { + if (MinNode == null) { + MinNode = node; + min_index = i; + } else if (node.Data < MinNode.Data) { + MinNode = node; + min_index = i; + } + } + } + if (pre == null) { + pre = MinNode; + head = MinNode; + } else { + pre.Next = MinNode; + pre = MinNode; + } + LinkedListNode next = lists.get(min_index).Next; + lists.set(min_index, next); + } + return head; + } + + public static void main(String[] args) { + ArrayList> lists = new ArrayList<>(); + lists.add(LinkedListNode.getSampleLinkedList()); + lists.add(LinkedListNode.getSampleLinkedList2()); + lists.add(LinkedListNode.getSampleLinkedList3()); + LinkedListNode solution = new Q52_MergeKSortedList().mergeKListsMy(lists); + LinkedListNode cur = solution; + while (cur != null) { + System.out.println(cur.Data); + cur = cur.Next; + } + } + + public LinkedListNode mergeKListsMy(ArrayList> lists) { + int len = lists.size(); + boolean pass = true; + LinkedListNode head = null, runner = null; + while (pass) { + pass = false; + LinkedListNode smallest = new LinkedListNode<>(Integer.MAX_VALUE); + int smallest_ind = 0; + for (int i = 0; i < len; i++) { + if (lists.get(i) != null) { + pass = true; + } + if (lists.get(i) != null && lists.get(i).Data < smallest.Data) { + smallest = lists.get(i); + smallest_ind = i; + } + } + if (pass) { + if (runner == null) { + runner = smallest; + } else { + runner.Next = smallest; + } + runner = smallest; + if (head == null) { + head = smallest; + } + lists.set(smallest_ind, lists.get(smallest_ind).Next); + } + } + return head; + } + + private LinkedListNode setSmallest(LinkedListNode a, LinkedListNode b) { + if (a == null) { + return b; + } else if (b == null) { + return a; + } + return a.Data >= b.Data ? b : a; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q53_MergeSortedArray.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q53_MergeSortedArray.java new file mode 100644 index 0000000..472335e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q53_MergeSortedArray.java @@ -0,0 +1,39 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q53_MergeSortedArray { + + public static void main(String[] args) { + int[] A = {1, 3, 5, 0, 0, 0}; + int[] B = {2, 4, 6}; + new Q53_MergeSortedArray().mergeMy(A, 3, B, 3); + for (int i : A) { + System.out.println(i); + } + } + + public void mergeMy(int A[], int m, int B[], int n) { + int k = m + n - 1, i = m - 1, j = n - 1; + while (true) { + if (i < 0) { + while (j >= 0) { + A[k--] = B[j--]; + } + break; + } else if (j < 0) { + while (i >= 0) { + A[k--] = A[i--]; + } + break; + } + + if (A[i] <= B[j]) { + A[k--] = B[j--]; + } else { + A[k--] = A[i--]; + } + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q54_MergeTwoSortedLists.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q54_MergeTwoSortedLists.java new file mode 100644 index 0000000..46f71b7 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q54_MergeTwoSortedLists.java @@ -0,0 +1,40 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q54_MergeTwoSortedLists { + + public static void main(String[] args) { + LinkedListNode l1 = LinkedListNode.getSampleLinkedList(); + LinkedListNode l2 = LinkedListNode.getSampleLinkedList2(); + LinkedListNode l = new Q54_MergeTwoSortedLists().mergeTwoListsMy(l1, l2); + l.print(); + } + + public LinkedListNode mergeTwoListsMy(LinkedListNode l1, LinkedListNode l2) { + if (l1 == null && l2 == null) { + return null; + } + LinkedListNode head = null; + if (l1 != null && l2 != null) { + if (l1.Data <= l2.Data) { + head = l1; + l1 = l1.Next; + } else { + head = l2; + l2 = l2.Next; + } + } else if (l2 != null) { + head = l2; + l2 = l2.Next; + } else if (l1 != null) { + head = l1; + l1 = l1.Next; + } + head.Next = mergeTwoListsMy(l1, l2); + return head; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q55_MinDepthBinaryTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q55_MinDepthBinaryTree.java new file mode 100644 index 0000000..60f3d93 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q55_MinDepthBinaryTree.java @@ -0,0 +1,72 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.LinkedList; +import java.util.Queue; + +public class Q55_MinDepthBinaryTree { + + public int minDepthRC(BinaryTreeNode root) { + if (root == null) { + return 0; + } + int l = minDepthRC(root.Left); + int r = minDepthRC(root.Right); + int result = 1 + Math.min(l, r); + return result; + } + + public int minDepth(BinaryTreeNode root) { + Queue q = new LinkedList<>(); + q.add(new Wrapper(root, 1)); + while (!q.isEmpty()) { + Wrapper wr = q.poll(); + BinaryTreeNode node = wr.node; + int level = wr.level; + if (node.Left == null && node.Right == null) { + return level; + } + if (node.Left != null) { + q.add(new Wrapper(node.Left, level + 1)); + } + if (node.Right != null) { + q.add(new Wrapper(node.Right, level + 1)); + } + } + return -1; + } + + class Wrapper { + + BinaryTreeNode node; + int level; + + public Wrapper(BinaryTreeNode _node, int _level) { + this.node = _node; + this.level = _level; + } + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + int level = new Q55_MinDepthBinaryTree().minDepth(root); + System.out.println(level); + int level2 = new Q55_MinDepthBinaryTree().minDepthRC(root); + System.out.println(level2); + int level3 = new Q55_MinDepthBinaryTree().minDepthMy(root); + System.out.println(level3); + } + + public int minDepthMy(BinaryTreeNode root) { + if (root == null) { + return 0; + } + int l = minDepthRC(root.Left); + int r = minDepthRC(root.Right); + int result = 1 + Math.min(l, r); + return result; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q56_MinPathSum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q56_MinPathSum.java new file mode 100644 index 0000000..4ba9ef1 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q56_MinPathSum.java @@ -0,0 +1,78 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; + +public class Q56_MinPathSum { + + public int minPathSumDP(int[][] grid) { + int i, j, height = grid.length, width = grid[0].length; + int dp[][] = new int[height][width]; + dp[0][0] = grid[0][0]; + for (i = 0; i < height; ++i) { + for (j = 0; j < width; ++j) { + if (i == 0 && j == 0) { + continue; + } + if (i == 0) { + dp[i][j] = dp[i][j - 1] + grid[i][j]; + } else if (j == 0) { + dp[i][j] = dp[i - 1][j] + grid[i][j]; + } else { + dp[i][j] = grid[i][j] + Math.min(dp[i][j - 1], dp[i - 1][j]); + } + } + } + return dp[height - 1][width - 1]; + } + + public int minPathSum(int[][] grid) { + int height = grid.length, width = grid[0].length; + return minPathSumHelper(grid, height - 1, width - 1); + } + + private int minPathSumHelper(int grid[][], int i, int j) { + if (i == 0 && j == 0) { + return grid[i][j]; + } else if (i == 0) { + return grid[i][j] + minPathSumHelper(grid, i, j - 1); + } else if (j == 0) { + return grid[i][j] + minPathSumHelper(grid, i - 1, j); + } else { + return grid[i][j] + Math.min(minPathSumHelper(grid, i - 1, j), minPathSumHelper(grid, i, j - 1)); + } + } + + public static void main(String[] args) { + int grid[][] = TestUtil.generateMatrix(10, 10, 5); + long l1 = System.currentTimeMillis(); + int sum1 = new Q56_MinPathSum().minPathSumMy(grid); + long l2 = System.currentTimeMillis(); + int sum2 = new Q56_MinPathSum().minPathSumDP(grid); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(sum1 + " Cost " + span1); + System.out.println(sum2 + " Cost " + span2); + } + + public int minPathSumMy(int[][] grid) { + int height = grid.length, width = grid[0].length, col, row; + int[][] tab = new int[height][width]; + tab[0][0] = grid[0][0]; + for (col = 1; col < height; col++) { + tab[col][0] = grid[col][0] + tab[col - 1][0]; + } + for (row = 1; row < width; row++) { + tab[0][row] = grid[0][row] + tab[0][row - 1]; + } + for (col = 1; col < height; col++) { + for (row = 1; row < width; row++) { + tab[col][row] = grid[col][row] + Math.min(tab[col][row - 1], tab[col - 1][row]); + } + } + + return tab[col - 1][row - 1]; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q57_MinWindowSubString.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q57_MinWindowSubString.java new file mode 100644 index 0000000..242d601 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q57_MinWindowSubString.java @@ -0,0 +1,94 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Queue; + +public class Q57_MinWindowSubString { + + public String MinimumWindowSubstring(String S, String T) { + int s_length = S.length(), t_length = T.length(); + HashMap> tab = new HashMap<>(); + int i, min_start = 0, min_length = s_length, ch_count = 0; + for (i = 0; i < t_length; i++) { + if (!tab.containsKey(T.charAt(i))) { + Queue q = new LinkedList<>(); + tab.put(T.charAt(i), q); + } + tab.get(T.charAt(i)).add(-1); + } + + for (i = 0; i < s_length; ++i) { + char ch = S.charAt(i); + if (tab.containsKey(ch)) { + Queue q = tab.get(ch); + if (q.peek() == -1) { + ++ch_count; + } + q.poll(); + q.add(i); + if (t_length == ch_count) { + int start = s_length; + for (Queue queue : tab.values()) { + if (queue.peek() < start) { + start = queue.peek(); + } + } + int len = i - start + 1; + if (len < min_length) { + min_length = len; + min_start = start; + } + } + } + } + return S.substring(min_start, min_start + min_length); + } + + public static void main(String[] args) { + String S = "abwwwaxxxxab"; + String T = "aab"; + String text = new Q57_MinWindowSubString().MinimumWindowSubstringMy(S, T); + System.out.println(text); + } + + public String MinimumWindowSubstringMy(String S, String T) { + HashMap> checker = new HashMap<>(); + int s_len = S.length(), t_len = T.length(), min_s = 0, min_len = Integer.MAX_VALUE, matched = 0, s = 0, e = 0; + for (int i = 0; i < t_len; i++) { + char ch = T.charAt(i); + if (!checker.containsKey(ch)) { + Queue temp = new LinkedList<>(); + checker.put(ch, temp); + } + checker.get(ch).add(-1); + } + for (int i = 0; i < s_len; i++) { + char ch = S.charAt(i); + if (checker.containsKey(ch)) { + if (checker.get(ch).peek() == -1) { + ++matched; + } + checker.get(ch).poll(); + checker.get(ch).add(i); + if (matched == t_len) { + int start = s_len; + for (Queue queue : checker.values()) { + if (queue.peek() < start) { + start = queue.peek(); + } + } + int cur_len = i - start + 1; + if (cur_len < min_len) { + min_len = cur_len; + min_s = start; + } + } + } + } + return S.substring(min_s, min_s + min_len); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q58_MultiplyString.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q58_MultiplyString.java new file mode 100644 index 0000000..ef838da --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q58_MultiplyString.java @@ -0,0 +1,63 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q58_MultiplyString { + + public String multiply(String num1, String num2) { + int a_length = num1.length(), b_length = num2.length(); + int solution[] = new int[b_length + a_length]; + int i, j, pre_carry = 0, next_carry = 0; + for (i = a_length - 1; i >= 0; --i) { + for (j = b_length - 1; j >= 0; --j) { + int a = num1.charAt(i) - '0'; + int b = num2.charAt(j) - '0'; + solution[a_length - 1 - i + b_length - 1 - j] += a * b; + } + } + for (i = 0; i < a_length + b_length; i++) { + next_carry = solution[i] / 10; + solution[i] = (solution[i] + pre_carry) % 10; + pre_carry = next_carry; + + } + int val = 0; + for (i = 0; i < a_length + b_length; ++i) { + val += Math.pow(10, i) * solution[i]; + } + return String.valueOf(val); + } + + public static void main(String[] args) { + String num1 = "12"; + String num2 = "23"; + String num = new Q58_MultiplyString().multiplyMy(num1, num2); + System.out.println(num); + } + + public String multiplyMy(String num1, String num2) { + int a_length = num1.length(), b_length = num2.length(), i, j; + int solution[] = new int[b_length + a_length]; + for (i = 0; i < a_length; i++) { + for (j = 0; j < b_length; j++) { + int n1 = num1.charAt(a_length - 1 - i) - '0'; + int n2 = num2.charAt(b_length - 1 - j) - '0'; + solution[i + j] += n1 * n2; + } + } + int carry = 0; + for (i = 0; i < a_length + b_length; i++) { + int sum = solution[i] + carry; + solution[i] = sum % 10; + carry = sum / 10; + } + + + int val = 0; + for (i = 0; i < a_length + b_length; ++i) { + val += Math.pow(10, i) * solution[i]; + } + return String.valueOf(val); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q59_NQueen.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q59_NQueen.java new file mode 100644 index 0000000..4b71732 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q59_NQueen.java @@ -0,0 +1,66 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q59_NQueen { + + public static void main(String[] args) { + ArrayList solution = new Q59_NQueen().solveNQueensMy(4); + for (String[] strings : solution) { + for (String string : strings) { + System.out.println(string); + } + System.out.println(); + } + } + + public ArrayList solveNQueensMy(int n) { + ArrayList solutions = new ArrayList<>(); + int[] board = new int[n]; + solveNqueensHelper(board, solutions, 0); + return solutions; + } + + private void solveNqueensHelper(int[] board, ArrayList solutions, int row) { + if (row == board.length) { + solutions.add(transform(board)); + return; + } + for (int i = 0; i < board.length; i++) { + board[row] = i; + if (checkBoard(board, row)) { + solveNqueensHelper(board, solutions, row + 1); + } + } + } + + private boolean checkBoard(int[] board, int row) { + for (int i = 0; i < row; i++) { + int dif_col = Math.abs(i - row); + int dif_row = Math.abs(board[row] - board[i]); + if (dif_col == dif_row || dif_row == 0) { + return false; + } + } + return true; + } + + private String[] transform(int[] board) { + String[] conv = new String[board.length]; + for (int i = 0; i < board.length; i++) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < board[i]; j++) { + sb.append("."); + } + sb.append("G"); + for (int j = board[i] + 1; j < board.length; j++) { + sb.append("."); + } + conv[i] = sb.toString(); + } + return conv; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q5_AddTwoNumber.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q5_AddTwoNumber.java new file mode 100644 index 0000000..96788d7 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q5_AddTwoNumber.java @@ -0,0 +1,35 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q5_AddTwoNumber { + + public LinkedListNode addTwoNumbers(LinkedListNode l1, LinkedListNode l2, int carry) { + if (carry == 0 && l1 == null & l2 == null) { + return null; + } + int sum = carry; + if (l1 != null) { + sum += l1.Data; + } + if (l2 != null) { + sum += l2.Data; + } + int digit = sum % 10; + int next_carry = sum / 10; + LinkedListNode node = new LinkedListNode<>(digit); + LinkedListNode next_node = addTwoNumbers(l1 != null ? l1.Next : null, l2 != null ? l2.Next : null, next_carry); + node.Next = next_node; + return node; + } + + public static void main(String[] args) { + LinkedListNode l1 = LinkedListNode.getSampleLinkedList2(); + LinkedListNode l2 = LinkedListNode.getSampleLinkedList2(); + LinkedListNode add = new Q5_AddTwoNumber().addTwoNumbers(l1, l2, 0); + add.print(); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q60_NQueen2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q60_NQueen2.java new file mode 100644 index 0000000..59732ea --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q60_NQueen2.java @@ -0,0 +1,48 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q60_NQueen2 { + + public static void main(String[] args) { + int ways = new Q60_NQueen2().solveNQueensMy(100000); + System.out.println(ways); + } + + public int solveNQueensMy(int n) { + int[] board = new int[n]; + IntWrapper iw = new IntWrapper(); + solveNqueensHelper(board, iw, 0); + return iw.i; + } + + class IntWrapper { + + int i = 0; + } + + private void solveNqueensHelper(int[] board, IntWrapper iw, int row) { + if (row == board.length) { + ++iw.i; + return; + } + for (int i = 0; i < board.length; i++) { + board[row] = i; + if (checkBoard(board, row)) { + solveNqueensHelper(board, iw, row + 1); + } + } + } + + private boolean checkBoard(int[] board, int row) { + for (int i = 0; i < row; i++) { + int dif_col = Math.abs(i - row); + int dif_row = Math.abs(board[row] - board[i]); + if (dif_col == dif_row || dif_row == 0) { + return false; + } + } + return true; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q61_NextPermutation.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q61_NextPermutation.java new file mode 100644 index 0000000..6fd73a7 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q61_NextPermutation.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q61_NextPermutation { + + public void nextPermutation(int[] num) { + int edge = -1; + for (int i = num.length - 2; i >= 0; i--) { + if (num[i] <= num[i + 1]) { + edge = i; + break; + } + } + if (edge > -1) { + for (int i = edge + 1; i < num.length; i++) { + if (num[edge] >= num[i]) { + swap(num, edge, i - 1); + break; + } + if (i == num.length - 1) { + swap(num, edge, i); + break; + } + } + } + for (int i = edge + 1, j = num.length - 1; i <= edge + (num.length - edge - 1) / 2; i++, j--) { + swap(num, i, j); + } + } + + private void swap(int[] num, int a, int b) { + int temp = num[a]; + num[a] = num[b]; + num[b] = temp; + } + + public static void main(String[] args) { + int num[] = {1, 2, 3, 456, 7, 8}; + new Q61_NextPermutation().nextPermutation(num); + for (int i : num) { + System.out.print(i); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q62_PalindromeNumber.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q62_PalindromeNumber.java new file mode 100644 index 0000000..decb305 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q62_PalindromeNumber.java @@ -0,0 +1,101 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q62_PalindromeNumber { + + public boolean isPalindrome1(int x) { + Wrapper wr = new Wrapper(x); + return isPalindrome1Helper(x, wr); + } + + private boolean isPalindrome1Helper(int x, Wrapper wr) { + if (x == 0) { + return true; + } + if (isPalindrome1Helper(x / 10, wr) && x % 10 == wr.x % 10) { + wr.x /= 10; + return true; + } else { + return false; + } + } + + class Wrapper { + + int x; + + public Wrapper(int _x) { + this.x = _x; + } + } + + public boolean isPalindrome2(int x) { + int div = 1; + while (x / div >= 10) { + div *= 10; + } + while (x > 0) { + int l = (x / div) % 10; + int r = x % 10; + if (l != r) { + return false; + } + x = (x % div) / 10; + div /= 100; + } + return true; + } + + public boolean isPalindromeEx(int x) { + int length = 0; + int r = x, i; + while (r > 0) { + r /= 10; + ++length; + } + for (i = 0; i < length / 2; ++i) { + if (getDigit(x, i) != getDigit(x, length - 1 - i)) { + return false; + } + } + return true; + } + + private int getDigit(int x, int i) { + while (i-- > 0) { + x /= 10; + } + return x % 10; + } + + public static void main(String[] args) { + int x = 121; + boolean ispalindrome = new Q62_PalindromeNumber().isPalindromeEx(x); + System.out.println(ispalindrome); + boolean ispalindrome2 = new Q62_PalindromeNumber().isPalindrome1(x); + System.out.println(ispalindrome2); + boolean ispalindrome3 = new Q62_PalindromeNumber().isPalindrome2(x); + System.out.println(ispalindrome3); + boolean ispalindrome4 = new Q62_PalindromeNumber().isPalindromeMy(x); + System.out.println(ispalindrome4); + } + static int num = -1; + + public boolean isPalindromeMy(int x) { + if ((x > 0 && x < 10) || x == 0) { + return true; + } + if (num == -1) { + num = x; + } + int r = x / 100; + boolean success = isPalindrome1(r); + if (num % 10 != r) { + success &= false; + } + num /= 100; + return success; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q63_PartitionList.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q63_PartitionList.java new file mode 100644 index 0000000..20320d5 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q63_PartitionList.java @@ -0,0 +1,49 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 22, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q63_PartitionList { + + public static void main(String[] args) { + LinkedListNode list = LinkedListNode.getSampleLinkedList7(); + LinkedListNode list2 = new Q63_PartitionList().partition(list, 1); + list2.print(); + } + + public LinkedListNode partition(LinkedListNode head, int x) { + LinkedListNode runner = head, next = head.Next, LS = null, LE = null, RS = null, RE = null; + while (runner != null) { + next = runner.Next; + + if (runner.Data <= x) { + if (LS == null) { + LS = runner; + LE = runner; + } else { + LE.Next = runner; + LE = runner; + } + } else { + if (RS == null) { + RS = runner; + RE = runner; + } else { + runner.Next = RS; + RS = runner; + } + } + + runner = next; + } + if (LE != null) { + LE.Next = RS; + } + if (RE != null) { + RE.Next = null; + } + return LS; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q64_PascalTriangle.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q64_PascalTriangle.java new file mode 100644 index 0000000..6c77fa8 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q64_PascalTriangle.java @@ -0,0 +1,65 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q64_PascalTriangle { + + public ArrayList> generate(int numRows) { + ArrayList> solution = new ArrayList>(); + for (int i = 0; i <= numRows; i++) { + ArrayList row = new ArrayList<>(); + if (i == 0) { + row.add(1); + } else { + ArrayList last_row = solution.get(i - 1); + for (int j = 0; j <= i; j++) { + if (j == 0) { + row.add(last_row.get(0)); + } else if (j == i) { + row.add(last_row.get(last_row.size() - 1)); + } else { + row.add(last_row.get(j - 1) + last_row.get(j)); + } + } + } + solution.add(row); + } + return solution; + } + + public static void main(String[] args) { + ArrayList> solution = new Q64_PascalTriangle().generateMy(9); + for (ArrayList arrayList : solution) { + for (Integer integer : arrayList) { + System.out.print(integer + " "); + } + System.out.println(); + } + } + + public ArrayList> generateMy(int numRows) { + ArrayList> solution = new ArrayList<>(); + for (int row = 0; row <= numRows; row++) { + ArrayList level = new ArrayList<>(); + if (row == 0) { + level.add(1); + } else { + ArrayList pre_solution = solution.get(row - 1); + for (int i = 0; i <= pre_solution.size(); i++) { + if (i == 0) { + level.add(1); + } else if (i == pre_solution.size()) { + level.add(1); + } else { + level.add(pre_solution.get(i) + pre_solution.get(i - 1)); + } + } + } + solution.add(level); + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q65_PascalTriangle2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q65_PascalTriangle2.java new file mode 100644 index 0000000..864cd7e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q65_PascalTriangle2.java @@ -0,0 +1,53 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q65_PascalTriangle2 { + + public ArrayList getRow(int rowIndex) { + ArrayList solution = new ArrayList<>(rowIndex); + solution.add(1); + int i, j; + for (i = 1; i < rowIndex; ++i) { + solution.add(0); + } + for (i = 2; i <= rowIndex; ++i) { + for (j = i - 1; j >= 1; --j) { + if (j == i) { + solution.set(j, solution.get(j - 1)); + } else { + solution.set(j, solution.get(j - 1) + solution.get(j)); + } + } + } + return solution; + } + + public static void main(String[] args) { + ArrayList solution = new Q65_PascalTriangle2().getRowMy(4); + for (Integer integer : solution) { + System.out.print(integer + " "); + } + } + + public ArrayList getRowMy(int rowIndex) { + ArrayList solution = new ArrayList<>(rowIndex); + for (int row = 0; row <= rowIndex; row++) { + if (row == 0) { + solution.add(1); + } else { + for (int i = row; i >= 1; i--) { + if (i == row) { + solution.add(1); + } else { + solution.set(i, solution.get(i) + solution.get(i - 1)); + } + } + } + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q66_PathSum.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q66_PathSum.java new file mode 100644 index 0000000..fe417dc --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q66_PathSum.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; + +public class Q66_PathSum { + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + boolean find = new Q66_PathSum().hasPathSum(root, 121); + System.out.println(find); + } + + public boolean hasPathSum(BinaryTreeNode root, int sum) { + int height = root.getHeight(); + RCHelper(root, new int[height], sum, 0); + return find; + + } + static boolean find = false; + + private void RCHelper(BinaryTreeNode head, int[] record, int sum, int level) { + if (find) { + return; + } + if (head == null) { + return; + } + + record[level] = head.Data; + int count = sum; + for (int i = level; i >= 0; i--) { + count -= record[i]; + if (count == 0) { + find = true; + return; + } + } + + RCHelper(head.Left, record, sum, level + 1); + RCHelper(head.Right, record, sum, level + 1); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q67_PathSum2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q67_PathSum2.java new file mode 100644 index 0000000..7aa24e2 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q67_PathSum2.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import java.util.ArrayList; + +public class Q67_PathSum2 { + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + ArrayList> solution = new Q67_PathSum2().pathSumMy(root, 12); + for (ArrayList arrayList : solution) { + for (Integer integer : arrayList) { + System.out.print(integer + " "); + } + System.out.println(); + } + } + + public ArrayList> pathSumMy(BinaryTreeNode root, int sum) { + ArrayList> solution = new ArrayList<>(); + int height = root.getHeight(); + RCHelper(root, new int[height], solution, sum, 0); + return solution; + } + + private void RCHelper(BinaryTreeNode head, int[] record, ArrayList> solution, int sum, int level) { + if (head == null) { + return; + } + record[level] = head.Data; + int count = sum; + for (int i = level; i >= 0; i--) { + count -= record[i]; + if (count == 0) { + //find it + ArrayList temp = new ArrayList<>(); + for (int j = i; j <= level; j++) { + temp.add(record[j]); + } + solution.add(temp); + } + } + + RCHelper(head.Left, record, solution, sum, level + 1); + RCHelper(head.Right, record, solution, sum, level + 1); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q68_PermutationSequence.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q68_PermutationSequence.java new file mode 100644 index 0000000..7db625f --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q68_PermutationSequence.java @@ -0,0 +1,12 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q68_PermutationSequence { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q69_Permutation.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q69_Permutation.java new file mode 100644 index 0000000..ccf78d4 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q69_Permutation.java @@ -0,0 +1,41 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q69_Permutation { + + public static void main(String[] args) { + int[] num = {1, 2, 3}; + ArrayList> solution = new Q69_Permutation().permuteEx(num, 0); + for (ArrayList arrayList : solution) { + for (Integer integer : arrayList) { + System.out.print(integer); + } + System.out.println(); + } + } + + public ArrayList> permuteEx(int[] num, int cur_ind) { + if (cur_ind == num.length - 1) { + ArrayList> solution = new ArrayList<>(); + ArrayList temp = new ArrayList<>(); + temp.add(num[cur_ind]); + solution.add(temp); + return solution; + } + ArrayList> solution = permuteEx(num, cur_ind + 1); + ArrayList> next_solution = new ArrayList<>(); + int digit = num[cur_ind]; + for (ArrayList arrayList : solution) { + for (int i = 0; i <= arrayList.size(); i++) { + ArrayList temp = (ArrayList) arrayList.clone(); + temp.add(i, digit); + next_solution.add(temp); + } + } + return next_solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q6_Anagrams.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q6_Anagrams.java new file mode 100644 index 0000000..5235749 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q6_Anagrams.java @@ -0,0 +1,43 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; +import java.util.HashMap; + +public class Q6_Anagrams { + + public ArrayList anagrams(String[] strs) { + ArrayList solutions = new ArrayList<>(); + HashMap> temp = new HashMap<>(); + + + for (String str : strs) { + String key = sortChars(str); + if (!temp.containsKey(key)) { + ArrayList temp_list = new ArrayList<>(); + temp.put(key, temp_list); + } + ArrayList temp_list = temp.get(key); + temp_list.add(str); + } + + for (String temp_key : temp.keySet()) { + if (temp.get(temp_key).size() >= 2) { + solutions.addAll(temp.get(temp_key)); + } + } + + return solutions; + } + + String sortChars(String str) { + char[] arr = str.toCharArray(); + java.util.Arrays.sort(arr); + return new String(arr); + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q70_Permutation2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q70_Permutation2.java new file mode 100644 index 0000000..90198b6 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q70_Permutation2.java @@ -0,0 +1,41 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q70_Permutation2 { + + public static void main(String[] args) { + int[] num = {1, 2, 3}; + ArrayList> solution = new Q70_Permutation2().permuteEx(num, 0); + for (ArrayList arrayList : solution) { + for (Integer integer : arrayList) { + System.out.print(integer); + } + System.out.println(); + } + } + + public ArrayList> permuteEx(int[] num, int cur_ind) { + if (cur_ind == num.length - 1) { + ArrayList> solution = new ArrayList<>(); + ArrayList temp = new ArrayList<>(); + temp.add(num[cur_ind]); + solution.add(temp); + return solution; + } + ArrayList> solution = permuteEx(num, cur_ind + 1); + ArrayList> next_solution = new ArrayList<>(); + int digit = num[cur_ind]; + for (ArrayList arrayList : solution) { + for (int i = 0; i <= arrayList.size(); i++) { + ArrayList temp = (ArrayList) arrayList.clone(); + temp.add(i, digit); + next_solution.add(temp); + } + } + return next_solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q71_PlusOne.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q71_PlusOne.java new file mode 100644 index 0000000..ca2c7c6 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q71_PlusOne.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q71_PlusOne { + + public int[] plusOne(int[] digits) { + int length = digits.length, i, carry = 0; + int solution[] = new int[length + 1]; + digits[length - 1] += 1; + for (i = length - 1; i >= 0; --i) { + solution[i + 1] = (carry + digits[i]) % 10; + carry = (carry + digits[i]) / 10; + } + if (carry > 0) { + solution[0] = carry; + } + return solution; + } + + public static void main(String[] args) { + int[] digits = {2, 9, 9}; + int[] solution = new Q71_PlusOne().plusOneMy(digits); + for (int i : solution) { + System.out.print(i); + } + } + + public int[] plusOneMy(int[] digits) { + int[] solution = new int[digits.length + 1]; + int carry = 0; + for (int i = digits.length - 1; i >= 0; i--) { + int sum = carry + digits[i]; + if (i == digits.length - 1) { + sum += 1; + } + int digit = sum % 10; + solution[i + 1] = digit; + carry = sum / 10; + } + if (carry > 0) { + solution[0] = carry; + } + return solution; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q72_PopulateNextRightPointerEachNode.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q72_PopulateNextRightPointerEachNode.java new file mode 100644 index 0000000..91ff36c --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q72_PopulateNextRightPointerEachNode.java @@ -0,0 +1,13 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q72_PopulateNextRightPointerEachNode { + + // the same as 73 + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q73_PopulateNextRightPointerEachNode2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q73_PopulateNextRightPointerEachNode2.java new file mode 100644 index 0000000..b13062f --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q73_PopulateNextRightPointerEachNode2.java @@ -0,0 +1,107 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q73_PopulateNextRightPointerEachNode2 { + + private void connect(TreeLinkNode node) { + if (node == null) { + return; + } + TreeLinkNode t = node, b = null, next = null; + + while (t != null) { + if (t.left != null) { + if (b == null) { + b = t.left; + } else { + b.next = t.left; + b = b.next; + } + if (next == null) { + next = node.left; + } + } + if (t.right != null) { + if (b == null) { + b = t.right; + } else { + b.next = t.right; + b = b.next; + } + if (next == null) { + next = t.right; + } + } + t = t.next; + } + connect(next); + } + + public class TreeLinkNode { + + int val; + TreeLinkNode left, right, next; + + TreeLinkNode(int x) { + val = x; + } + } + + public static void main(String[] args) { + Q73_PopulateNextRightPointerEachNode2 q73 = new Q73_PopulateNextRightPointerEachNode2(); + TreeLinkNode tln1 = q73.new TreeLinkNode(1); + TreeLinkNode tln2 = q73.new TreeLinkNode(2); + TreeLinkNode tln3 = q73.new TreeLinkNode(3); + TreeLinkNode tln4 = q73.new TreeLinkNode(4); + TreeLinkNode tln5 = q73.new TreeLinkNode(5); + TreeLinkNode tln6 = q73.new TreeLinkNode(6); + TreeLinkNode tln7 = q73.new TreeLinkNode(7); + TreeLinkNode tln8 = q73.new TreeLinkNode(8); + tln1.left = tln2; + tln1.right = tln3; + tln2.left = tln4; + tln2.right = tln5; + tln3.right = tln6; + tln4.left = tln7; + tln4.right = tln8; + q73.connectMy(tln1); + System.out.println(); + } + + private void connectMy(TreeLinkNode node) { + TreeLinkNode horizontal = node, vertical = node, last = null; + while (vertical != null) { + horizontal = vertical; + TreeLinkNode next = null; + last = null; + while (horizontal != null) { + if (horizontal.left != null) { + if (last == null) { + last = horizontal.left; + } else { + last.next = horizontal.left; + last = horizontal.left; + } + if (next == null) { + next = horizontal.left; + } + } + if (horizontal.right != null) { + if (last == null) { + last = horizontal.right; + } else { + last.next = horizontal.right; + last = horizontal.right; + } + if (next == null) { + next = last.right; + } + } + horizontal = horizontal.next; + } + vertical = next; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q74_Pow.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q74_Pow.java new file mode 100644 index 0000000..e8acf79 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q74_Pow.java @@ -0,0 +1,65 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q74_Pow { + + public double pow(double x, int n) { + boolean neg = false; + if (n < 0) { + neg = true; + n = -n; + } + double result = 1; + for (int i = 0; i < n; i++) { + result *= x; + } + if (neg) { + return 1 / result; + } else { + return result; + } + } + + public double powBinary(double x, int n) { + if (n < 0) { + return 1 / powBinaryHelper(x, -n); + } else { + return powBinaryHelper(x, n); + } + } + + public double powBinaryHelper(double x, int n) { + if (n == 0) { + return 1; + } + double val = powBinaryHelper(x, n / 2); + if (n % 2 == 0) { + return val * val; + } else { + return val * val * x; + } + } + + public static void main(String[] args) { + double result = new Q74_Pow().pow(2, 10); + double result2 = new Q74_Pow().powBinary(2, 4); + System.out.println(result); + System.out.println(result2); + double result3 = new Q74_Pow().powMy(2, 4); + System.out.println(result3); + } + + public double powMy(double x, int n) { + if (n == 0) { + return 1; + } + double val = powMy(x, n >> 1); + if (n % 2 == 0) { + return val * val; + } else { + return val * val * x; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q75_RecoverBinarySearchTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q75_RecoverBinarySearchTree.java new file mode 100644 index 0000000..03a8972 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q75_RecoverBinarySearchTree.java @@ -0,0 +1,116 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; +import com.sun.org.apache.bcel.internal.generic.BREAKPOINT; + +public class Q75_RecoverBinarySearchTree { + + public void recoverTree(BinaryTreeNode root) { + Wrapper wr1 = new Wrapper(); + recoverTreeFindL(root, wr1); + Wrapper wr2 = new Wrapper(); + recoverTreeFindR(root, wr2); + System.out.println(wr1.node.Data + "<->" + wr2.node.Data); + int temp = wr1.node.Data; + wr1.node.Data = wr2.node.Data; + wr2.node.Data = temp; + } + + private void recoverTreeFindL(BinaryTreeNode root, Wrapper wr) { + if (root == null) { + return; + } + recoverTreeFindL(root.Left, wr); + if (wr.node == null) { + wr.node = root; + } else { + if (root.Data < wr.node.Data) { + return; + } + wr.node = root; + } + recoverTreeFindL(root.Right, wr); + } + + private void recoverTreeFindR(BinaryTreeNode root, Wrapper wr) { + if (root == null) { + return; + } + recoverTreeFindR(root.Right, wr); + if (wr.node == null) { + wr.node = root; + } else { + if (root.Data > wr.node.Data) { + return; + } + wr.node = root; + } + recoverTreeFindR(root.Left, wr); + } + + class Wrapper { + + BinaryTreeNode node; + + public Wrapper(BinaryTreeNode _node) { + this.node = _node; + } + + public Wrapper() { + } + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + root.Left.Data = 17; + root.Right.Right.Data = 5; + new Q75_RecoverBinarySearchTree().recoverTreeMy(root); + System.out.println(); + } + + public void recoverTreeMy(BinaryTreeNode root) { + findLeft(root); + last = null; + findRight(root); + int temp = find1.Data; + find1.Data = find2.Data; + find2.Data = temp; + } + BinaryTreeNode find1 = null, find2 = null, last = null; + + private void findLeft(BinaryTreeNode root) { + if (root == null) { + return; + } + findLeft(root.Left); + if (last == null) { + last = root; + } + if (last.Data > root.Data) { + + find1 = last; + return; + } + last = root; + findLeft(root.Right); + } + + private void findRight(BinaryTreeNode root) { + if (root == null) { + return; + } + findRight(root.Right); + if (last == null) { + last = root; + } + if (last.Data < root.Data) { + find2 = last; + return; + } + last = root; + findRight(root.Left); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q76_RegularExpressionMatching.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q76_RegularExpressionMatching.java new file mode 100644 index 0000000..d85ed17 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q76_RegularExpressionMatching.java @@ -0,0 +1,109 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 23, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q76_RegularExpressionMatching { + + public boolean isMatch(String s, String p) { + int s_length = s.length(), p_length = p.length(); + if (s_length == 0) { + return checkempty(p); + } + if (p_length == 0) { + return false; + } + char c1 = s.charAt(0); + char p1 = p.charAt(0), p2 = '\0'; + if (p_length > 1) { + p2 = p.charAt(1); + } + if (p2 == '*') { + if (p1 == '.' || c1 == p1) { + return isMatch(s.substring(1), p)||isMatch(s, p.substring(2)); + } else { + return isMatch(s, p.substring(2)); + } + } else { + if (p1 == '.' || c1 == p1) { + return isMatch(s.substring(1), p.substring(1)); + } else { + return false; + } + } + } + + private boolean checkempty(String p) { + if ((p.length() % 2) != 0) { + return false; + } + for (int i = 1; i < p.length(); i += 2) { + if (p.charAt(i) != '*') { + return false; + } + } + return true; + } + + public boolean isMatchSample(String s, String p) { + //Java note: s.substring(n) will be "" if n == s.length(), but if n > s.length(), index oob error + // Start typing your Java solution below + // DO NOT write main() function + + int i = 0, j = 0; + //you don't have to construct a state machine for this problem + + if (s.length() == 0) { + return checkEmpty(p); + } + + if (p.length() == 0) { + return false; + } + + char c1 = s.charAt(0); + char d1 = p.charAt(0), d2 = '0'; //any init value except '*'for d2 will do + + if (p.length() > 1) { + d2 = p.charAt(1); + } + + if (d2 == '*') { + if (d1 == '.' || c1 == d1) { + //fork here: 1. consume the character, and use the same pattern again. + //2. keep the character, and skip 'd1*' pattern + + //Here is also an opportunity to use DP, but the idea is the same + return isMatch(s.substring(1), p) || isMatch(s, p.substring(2)); + } else { + return isMatch(s, p.substring(2)); + } + } else { + if (d1 == '.' || c1 == d1) { + return isMatch(s.substring(1), p.substring(1)); + } else { + return false; + } + } + } + + public boolean checkEmpty(String p) { + if (p.length() % 2 != 0) { + return false; + } + + for (int i = 1; i < p.length(); i += 2) { + if (p.charAt(i) != '*') { + return false; + } + } + return true; + } + + public static void main(String[] args) { + String s = "aab"; + String p = "*"; + boolean result = new Q76_RegularExpressionMatching().isMatch(s, p); + System.out.println(result); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q77_RemoveDuplicateInSortedArray.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q77_RemoveDuplicateInSortedArray.java new file mode 100644 index 0000000..133ba2d --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q77_RemoveDuplicateInSortedArray.java @@ -0,0 +1,42 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q77_RemoveDuplicateInSortedArray { + + public int removeDuplicates(int[] A) { + int length = A.length, i, j = 0; + for (i = 1; i < length; i++) { + if (A[i] != A[i - 1]) { + A[++j] = A[i]; + } + } + A[++j] = A[i - 1]; + return j; + } + + public static void main(String[] args) { + int A[] = {1, 1, 1, 2, 2, 3, 3, 3}; + int length = new Q77_RemoveDuplicateInSortedArray().removeDuplicatesMy(A); + for (int i : A) { + System.out.print(i); + } + System.out.println("len:" + length); + } + + public int removeDuplicatesMy(int[] A) { + int len = A.length, pos = 0; + for (int i = 1; i < len; i++) { + if (A[i] == A[pos]) { + } else { + A[++pos] = A[i]; + } + } + A[++pos] = A[len - 1]; + if (pos < len) { + A[pos] = 0; + } + return pos; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q78_RemoveDuplicateInSortedArray2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q78_RemoveDuplicateInSortedArray2.java new file mode 100644 index 0000000..e73b684 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q78_RemoveDuplicateInSortedArray2.java @@ -0,0 +1,68 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.concurrent.CountDownLatch; + +public class Q78_RemoveDuplicateInSortedArray2 { + + public int removeDuplicates(int[] A) { + int length = A.length, i, j = 0, count = 1; + for (i = 1; i < length; i++) { + if (A[i] == A[i - 1]) { + if (count < 2) { + ++count; + } + } else { + if (count == 1) { + A[j++] = A[i - 1]; + } else if (count == 2) { + A[j++] = A[i - 1]; + A[j++] = A[i - 1]; + } + count = 1; + } + } + if (count == 1) { + A[j++] = A[i - 1]; + } else if (count == 2) { + A[j++] = A[i - 1]; + A[j++] = A[i - 1]; + } + return j; + } + + public static void main(String[] args) { + int A[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4}; + int length = new Q78_RemoveDuplicateInSortedArray2().removeDuplicatesMy(A); + for (int i : A) { + System.out.print(i); + } + System.out.println("len:" + length); + } + + public int removeDuplicatesMy(int[] A) { + int len = A.length, ind = 1, pos = 0, count = 0;; + while (ind < len) { + if (A[ind] == A[ind - 1]) { + if (count < 2) { + ++count; + } + } else { + for (int i = 0; i < count; i++) { + A[pos++] = A[ind - 1]; + } + count = 1; + } + ++ind; + } + for (int i = 0; i < count; i++) { + A[pos++] = A[ind - 1]; + } + if (pos < len) { + A[pos] = -1; + } + return pos; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q79_RemoveDuplicateInSortedList.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q79_RemoveDuplicateInSortedList.java new file mode 100644 index 0000000..f2c066d --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q79_RemoveDuplicateInSortedList.java @@ -0,0 +1,53 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; +import java.util.HashMap; +import java.util.HashSet; + +public class Q79_RemoveDuplicateInSortedList { + + public LinkedListNode deleteDuplicates(LinkedListNode head) { + LinkedListNode runner = head, next = null; + /* Note here: Cannot update more than one + * while (runner != null) { + next = runner.Next; + if (next != null && next.Data == runner.Data) { + runner.Next = next.Next; + } + runner = next; + }*/ + while (runner != null) { + next = runner.Next; + while (next != null && next.Data == runner.Data) { + next = next.Next; + } + runner.Next = next; + runner = next; + } + return head; + } + + public static void main(String[] args) { + LinkedListNode n1 = LinkedListNode.getSampleLinkedList4(); + new Q79_RemoveDuplicateInSortedList().deleteDuplicatesMy(n1); + n1.print(); + } + + public LinkedListNode deleteDuplicatesMy(LinkedListNode head) { + LinkedListNode runner = head, newhead = head, loop; + + while (runner != null) { + loop = runner.Next; + while (loop != null && loop.Data == runner.Data) { + loop = loop.Next; + } + runner.Next = loop; + runner = loop; + } + + return newhead; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q7_BalancedBinaryTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q7_BalancedBinaryTree.java new file mode 100644 index 0000000..4e1f824 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q7_BalancedBinaryTree.java @@ -0,0 +1,34 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q7_BalancedBinaryTree { + + public int isBalancedHelper(BinaryTreeNode root) { + if (root == null) { + return 0; + } + int l = isBalancedHelper(root.Left); + if (l == -1) { + return -1; + } + int r = isBalancedHelper(root.Right); + if (r == -1) { + return -1; + } + int dis = Math.abs(l - r); + if (dis > 1) { + return -1; + } + return 1 + dis; + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree3(); + int result = new Q7_BalancedBinaryTree().isBalancedHelper(root); + System.out.println(result); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q80_RemoveDuplicateInSortedList2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q80_RemoveDuplicateInSortedList2.java new file mode 100644 index 0000000..bc3388e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q80_RemoveDuplicateInSortedList2.java @@ -0,0 +1,63 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q80_RemoveDuplicateInSortedList2 { + + public LinkedListNode deleteDuplicates(LinkedListNode head) { + LinkedListNode solution = new LinkedListNode<>(0); + LinkedListNode runner = head, pre = solution; + solution.Next = head; + while (runner != null) { + boolean dup = false; + while (runner.Next != null && runner.Next.Data == runner.Data) { + dup = true; + runner = runner.Next; + } + if (dup) { + runner = runner.Next; + pre.Next = runner; + } else { + pre = runner; + runner = runner.Next; + } + } + return solution.Next; + } + + public static void main(String[] args) { + LinkedListNode n1 = LinkedListNode.getSampleLinkedList4(); + n1.print(); + System.out.println("-=-=-=-=-=-=-"); + LinkedListNode n2 = new Q80_RemoveDuplicateInSortedList2().deleteDuplicatesMy(n1); + n2.print(); + } + + public LinkedListNode deleteDuplicatesMy(LinkedListNode head) { + LinkedListNode runner = head, newhead = new LinkedListNode<>(Integer.MIN_VALUE), loop, last = newhead; + newhead.Next = runner; + boolean duplicate = false; + while (runner != null) { + duplicate = false; + + loop = runner.Next; + while (loop != null && loop.Data == runner.Data) { + duplicate = true; + loop = loop.Next; + } + + if (duplicate) { + last.Next = loop; + runner = loop; + } else { + last = runner; + runner = runner.Next; + } + } + + return newhead.Next; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q81_RemoveElement.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q81_RemoveElement.java new file mode 100644 index 0000000..e8976e0 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q81_RemoveElement.java @@ -0,0 +1,60 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; + +public class Q81_RemoveElement { + + public int removeElement(int[] A, int elem) { + int s = 0, length = A.length, e = length - 1; + while (s < e) { + for (; s < e && A[s] != elem; ++s); + for (; s < e && A[e] == elem; --e); + int temp = A[s]; + A[s] = A[e]; + A[e] = temp; + } + return s; + } + + public int removeElementEx(int[] A, int elem) { + int length = A.length, i, j = 0; + for (i = 0; i < length; i++) { + if (A[i] != elem) { + A[j++] = A[i]; + } + } + return j; + } + + public static void main(String[] args) { + int A[] = {1, 3, 2, 3, 4, 3, 5, 6, 3}; + int len = new Q81_RemoveElement().removeElementMy(A, 3); + for (int i : A) { + System.out.print(i); + } + System.out.println("len:" + len); + + int test[] = TestUtil.generateArray(99999999, 9, false); + long l1 = System.currentTimeMillis(); + int t1 = new Q81_RemoveElement().removeElement(test, 5); + long l2 = System.currentTimeMillis(); + int t2 = new Q81_RemoveElement().removeElementEx(test, 5); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(t1 + " Cost " + span1); + System.out.println(t2 + " Cost " + span2); + } + + public int removeElementMy(int[] A, int elem) { + int len = A.length, pos = 0; + for (int i = 0; i < len; i++) { + if (A[i] != elem) { + A[pos++] = A[i]; + } + } + return pos; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q82_RemoveNthNodeFromEndOfList.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q82_RemoveNthNodeFromEndOfList.java new file mode 100644 index 0000000..333ddda --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q82_RemoveNthNodeFromEndOfList.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q82_RemoveNthNodeFromEndOfList { + + public LinkedListNode removeNthFromEnd(LinkedListNode head, int n) { + LinkedListNode left = head; + LinkedListNode right = head; + int i; + for (i = 0; i < n + 1; ++i) { + right = right.Next; + } + while (right != null) { + left = left.Next; + right = right.Next; + } + left.Next = left.Next.Next; + return head; + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList(); + head.print(); + LinkedListNode head2 = new Q82_RemoveNthNodeFromEndOfList().removeNthFromEndMy(head, 7); + head2.print(); + } + + public LinkedListNode removeNthFromEndMy(LinkedListNode head, int n) { + LinkedListNode left = head; + LinkedListNode right = head; + for (int i = 0; i < n + 1; i++) { + right = right.Next; + if (right == null) { + return head.Next; + } + } + while (right != null) { + left = left.Next; + right = right.Next; + } + if (left != null && left.Next != null) { + left.Next = left.Next.Next; + } + return head; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q83_RestoreIPAddress.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q83_RestoreIPAddress.java new file mode 100644 index 0000000..bdc055b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q83_RestoreIPAddress.java @@ -0,0 +1,118 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.ArrayList; + +public class Q83_RestoreIPAddress { + + public ArrayList restoreIpAddresses(String s) { + ArrayList solution = new ArrayList<>(); + int dot1, dot2, dot3, length = s.length(); + for (dot1 = 1; dot1 < length; ++dot1) { + for (dot2 = dot1 + 1; dot2 < length; ++dot2) { + for (dot3 = dot2 + 1; dot3 < length; ++dot3) { + if (isValidate(s.substring(0, dot1)) + && isValidate(s.substring(dot1, dot2)) + && isValidate(s.substring(dot2, dot3)) + && isValidate(s.substring(dot3, length - 1))) { + StringBuilder sb = new StringBuilder(); + sb.append(s.substring(0, dot1)).append(".").append(s.substring(dot1, dot2)) + .append(".").append(s.substring(dot2, dot3)).append(".").append(s.substring(dot3, length - 1)); + solution.add(sb.toString()); + } + } + } + } + return solution; + } + + private boolean isValidate(String ip) { + int length = ip.length(); + if (length > 3) { + return false; + } + if (length == 3) { + return ip.charAt(0) >= '1' && ip.charAt(0) <= '2' + && ip.charAt(1) >= '0' && ip.charAt(1) <= '9' + && ip.charAt(2) >= '0' && ip.charAt(2) <= '9'; + } else if (length == 2) { + return ip.charAt(0) >= '1' && ip.charAt(0) <= '9' + && ip.charAt(1) >= '0' && ip.charAt(1) <= '9'; + } else { + return ip.charAt(0) >= '1' && ip.charAt(0) <= '9'; + } + } + + public static void main(String[] args) { + String s = "25525511135"; + ArrayList solution = new Q83_RestoreIPAddress().restoreIpAddressesMy(s); + for (String string : solution) { + System.out.println(string); + } + } + + //most correct one + public ArrayList restoreIpAddressesMy(String s) { + ArrayList solution = new ArrayList<>(); + int dot1, dot2, dot3, len = s.length(); + for (dot1 = 0; dot1 < len - 3; dot1++) { + for (dot2 = dot1 + 1; dot2 < len - 2; dot2++) { + for (dot3 = dot2 + 1; dot3 < len - 1; dot3++) { + if (validateIP(s.substring(0, dot1)) + && validateIP(s.substring(dot1, dot2)) + && validateIP(s.substring(dot2, dot3)) + && validateIP(s.substring(dot3, len))) { + StringBuilder sb = new StringBuilder(); + sb.append(s.substring(0, dot1)).append("."); + sb.append(s.substring(dot1, dot2)).append("."); + sb.append(s.substring(dot2, dot3)).append("."); + sb.append(s.substring(dot3, len)); + solution.add(sb.toString()); + } + } + } + } + return solution; + } + + boolean validateIP(String IP) { + int len = IP.length(); + if (len <= 0 || len > 3) { + return false; + } + if (len == 3) { + if (IP.charAt(0) > '2' || IP.charAt(0) <= '0') { + return false; + } + if (IP.charAt(0) == '2') { + if (IP.charAt(1) > '5' || IP.charAt(1) < '0') { + return false; + } + if (IP.charAt(2) > '6' || IP.charAt(2) < '0') { + return false; + } + } else { + if (IP.charAt(1) > '9' || IP.charAt(1) < '0') { + return false; + } + if (IP.charAt(2) > '9' || IP.charAt(2) < '0') { + return false; + } + } + } else if (len == 2) { + if (IP.charAt(0) > '9' || IP.charAt(0) <= '0') { + return false; + } + if (IP.charAt(1) > '9' || IP.charAt(1) < '0') { + return false; + } + } else if (len == 1) { + if (IP.charAt(0) > '9' || IP.charAt(0) < '0') { + return false; + } + } + return true; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q84_ReverseInteger.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q84_ReverseInteger.java new file mode 100644 index 0000000..78300ab --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q84_ReverseInteger.java @@ -0,0 +1,46 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q84_ReverseInteger { + + public int reverse(int x) { + boolean neg = false; + if (x < 0) { + x = -x; + neg = true; + } + int solution = 0; + while (x > 0) { + int d = x % 10; + solution *= 10; + solution += d; + x = x / 10; + } + return solution; + } + + public static void main(String[] args) { + int solution = new Q84_ReverseInteger().reverseMy(-12345); + System.out.println(solution); + } + + public int reverseMy(int x) { + boolean neg = false; + if (x < 0) { + neg = true; + x = -x; + } + int num = 0; + while (x > 0) { + num *= 10; + num += x % 10; + x /= 10; + } + if (neg) { + num *= -1; + } + return num; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q85_ReverseLinkedList2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q85_ReverseLinkedList2.java new file mode 100644 index 0000000..9203843 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q85_ReverseLinkedList2.java @@ -0,0 +1,65 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q85_ReverseLinkedList2 { + + public LinkedListNode reverseBetween(LinkedListNode head, int m, int n) { + int i = 1; + LinkedListNode start_l = null, start_r = null, end_l = null, end_r = null, runner = head, last = null, next = head.Next; + while (next != null) { + if (i == m) { + start_l = last; + end_l = runner; + } + if (i == n) { + start_r = runner; + end_r = next; + } + if (i > m && i <= n) { + runner.Next = last; + } + last = runner; + runner = next; + next = next.Next; + ++i; + } + start_l.Next = start_r; + end_l.Next = end_r; + return head; + } + + public static void main(String[] args) { + LinkedListNode root = LinkedListNode.getSampleLinkedList(); + root.print(); + System.out.println("-=-=-=-=-=-=-"); + LinkedListNode root2 = new Q85_ReverseLinkedList2().reverseBetweenMy(root, 1, 4); + root2.print(); + } + + //most correct one + public LinkedListNode reverseBetweenMy(LinkedListNode head, int m, int n) { + LinkedListNode solution = new LinkedListNode<>(0), cur = head, pre = solution, next = head.Next, LS = null, LE = null; + solution.Next = head; + int a = m, b = n; + while (--a > 0) { + next = cur.Next; + pre = cur; + cur = next; + } + LS = pre; + LE = cur; + while (b-- >= m) { + next = cur.Next; + cur.Next = pre; + pre = cur; + cur = next; + } + LS.Next = pre; + LE.Next = cur; + return solution.Next; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q86_ReverseNodesInKGroup.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q86_ReverseNodesInKGroup.java new file mode 100644 index 0000000..073cbf8 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q86_ReverseNodesInKGroup.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q86_ReverseNodesInKGroup { + + public LinkedListNode reverseKGroup(LinkedListNode head, int k) { + LinkedListNode pre = null, cur = head, next = head.Next; + int count = 0; + while (cur != null) { + cur.Next = pre; + if (++count == k) { + break; + } + pre = cur; + cur = next; + if (next != null) { + next = next.Next; + } + } + head.Next = next; + return cur; + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList(); + head.print(); + System.out.println("-=-=-=-=-=-=-"); + LinkedListNode head2 = new Q86_ReverseNodesInKGroup().reverseKGroupMy(head, 3); + head2.print(); + } + + public LinkedListNode reverseKGroupMy(LinkedListNode head, int k) { + LinkedListNode pre_head = new LinkedListNode<>(0); + pre_head.Next = head; + LinkedListNode pre = pre_head, cur = head, next = head.Next; + while (k-- > 0) { + next = cur.Next; + cur.Next = pre; + pre = cur; + cur = next; + } + pre_head.Next.Next = cur; + pre_head.Next = pre; + return pre_head.Next; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q87_RomanToInteger.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q87_RomanToInteger.java new file mode 100644 index 0000000..26fcb2b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q87_RomanToInteger.java @@ -0,0 +1,70 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.HashMap; + +public class Q87_RomanToInteger { + + public int romanToInt(String s) { + HashMap map = new HashMap(); + map.put('I', 1); + map.put('V', 5); + map.put('X', 10); + map.put('L', 50); + map.put('C', 100); + map.put('D', 500); + map.put('M', 1000); + int result = 0, i, length = s.length(); + for (i = 0; i < length; i++) { + result += map.get(s.charAt(i)) * signature(s, i, map); + } + return result; + } + + private short signature(String s, int i, HashMap map) { + int length = s.length(); + if (i == length - 1) { + return 1; + } + if (map.get(s.charAt(i + 1)) > map.get(s.charAt(i))) { + return -1; + } else { + return 1; + } + } + + public static void main(String[] args) { + String val = "IV"; + int num = new Q87_RomanToInteger().romanToIntMy(val); + System.out.println(num); + } + + public int romanToIntMy(String s) { + HashMap map = new HashMap(); + map.put('I', 1); + map.put('V', 5); + map.put('X', 10); + map.put('L', 50); + map.put('C', 100); + map.put('D', 500); + map.put('M', 1000); + int result = 0, i, length = s.length(); + for (i = 0; i < length; i++) { + result += map.get(s.charAt(i)) * signature(s, i, map); + } + return result; + } + + short signMy(String s, int i, HashMap map) { + if (i + 1 == s.length()) { + return 1; + } + if (map.get(s.charAt(i + 1)) > map.get(s.charAt(i))) { + return -1; + } else { + return 1; + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q88_RotateImage.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q88_RotateImage.java new file mode 100644 index 0000000..654d508 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q88_RotateImage.java @@ -0,0 +1,38 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q88_RotateImage { + + public static void main(String[] args) { + int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2}, {3, 4, 5, 6}}; + for (int col = 0; col < matrix.length; col++) { + for (int row = 0; row < matrix[0].length; row++) { + System.out.print(matrix[col][row] + " "); + } + System.out.println(); + } + System.out.println(); + new Q88_RotateImage().rotateMy(matrix); + for (int col = 0; col < matrix.length; col++) { + for (int row = 0; row < matrix[0].length; row++) { + System.out.print(matrix[col][row] + " "); + } + System.out.println(); + } + } + + public void rotateMy(int[][] matrix) { + int edge = matrix.length; + for (int layer = 0; layer < edge / 2; layer++) { + for (int i = layer; i < edge - layer - 1; i++) { + int temp = matrix[layer][layer + i]; + matrix[layer][layer + i] = matrix[edge - 1 - layer - i][layer]; + matrix[edge - 1 - layer - i][layer] = matrix[edge - 1 - layer][edge - 1 - layer - i]; + matrix[edge - 1 - layer][edge - 1 - layer - i] = matrix[layer + i][edge - 1 - layer]; + matrix[layer + i][edge - 1 - layer] = temp; + } + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q89_RotateList.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q89_RotateList.java new file mode 100644 index 0000000..80dd13e --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q89_RotateList.java @@ -0,0 +1,48 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.LinkedListNode; + +public class Q89_RotateList { + + public LinkedListNode rotateRight(LinkedListNode head, int n) { + LinkedListNode loop = head; + int count = 1; + while (count++ != n) { + loop = loop.Next; + } + LinkedListNode NewHead = loop.Next; + loop.Next = null; + loop = NewHead; + while (loop.Next != null) { + loop = loop.Next; + } + loop.Next = head; + return NewHead; + } + + public static void main(String[] args) { + LinkedListNode list = LinkedListNode.getSampleLinkedList(); + list.print(); + System.out.println("-=-=-=-=-=-=-"); + LinkedListNode new_list = new Q89_RotateList().rotateRightMy(list, 3); + new_list.print(); + } + + public LinkedListNode rotateRightMy(LinkedListNode head, int n) { + LinkedListNode left = head, right = head, newhead = null; + while (n-- > 0) { + right = right.Next; + } + while (right.Next != null) { + left = left.Next; + right = right.Next; + } + newhead = left.Next; + left.Next = null; + right.Next = head; + return newhead; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q8_BestTimeBuySellStock.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q8_BestTimeBuySellStock.java new file mode 100644 index 0000000..08e6fbd --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q8_BestTimeBuySellStock.java @@ -0,0 +1,44 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q8_BestTimeBuySellStock { + + public int maxProfit(int[] prices) { + int MaxProfitVal = Integer.MIN_VALUE, i = 1, length = prices.length; + int buy_day = 0; + for (; i < length; ++i) { + int profit = prices[i] - prices[buy_day]; + if (profit > MaxProfitVal) { + MaxProfitVal = profit; + } + buy_day = prices[i] < prices[buy_day] ? i : buy_day; + } + return MaxProfitVal; + + } + + //my way + public int maxProfitEx(int[] prices) { + int max = Integer.MIN_VALUE; + int i, length = prices.length; + int buy_date = 0; + for (i = 1; i < length; i++) { + if (prices[i] < prices[buy_date]) { + buy_date = i; + } + max = Math.max(max, prices[i] - prices[buy_date]); + } + return max; + } + + public static void main(String[] args) { + int[] prices = {1, 2, 3, 9, 3, 4, 2, 1, 10}; + int profit = new Q8_BestTimeBuySellStock().maxProfit(prices); + System.out.println(profit); + + int profit2 = new Q8_BestTimeBuySellStock().maxProfitEx(prices); + System.out.println(profit2); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q90_SameTree.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q90_SameTree.java new file mode 100644 index 0000000..3d321dd --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q90_SameTree.java @@ -0,0 +1,35 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.BinaryTreeNode; + +public class Q90_SameTree { + + public static void main(String[] args) { + } + + public boolean isSameTreeMy(BinaryTreeNode p, BinaryTreeNode q) { + if (p == null) { + return false; + } + if (p.Data == q.Data && isSameTreeMyHelper(p, q)) { + return true; + } + return isSameTreeMy(p.Left, q) || isSameTreeMy(p.Right, q); + } + + private boolean isSameTreeMyHelper(BinaryTreeNode p, BinaryTreeNode q) { + if (p == null && q == null) { + return true; + } else if ((p == null && q != null) || (q == null && p == null)) { + return false; + } else { + if (p.Data != q.Data) { + return false; + } + return isSameTreeMyHelper(p.Left, q.Left) && isSameTreeMyHelper(p.Right, q.Right); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q91_ScrambleString.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q91_ScrambleString.java new file mode 100644 index 0000000..9dad7fa --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q91_ScrambleString.java @@ -0,0 +1,79 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q91_ScrambleString { + + public boolean isScramble(String s1, String s2) { + int s2_length = s2.length(), s1_length = s1.length(); + if (s1.equals(s2)) { + return true; + } else if (s1_length != s2_length) { + return false; + } else if (s1_length == 1 && (!s1.equals(s2))) { + return false; + } else { + for (int i = 1; i <= s1_length / 2; i++) { + String a1 = s1.substring(0, i); + String b1 = s1.substring(i); + String a2 = s2.substring(0, i); + String b2 = s2.substring(i); + String c1 = s1.substring(0, s1_length - i); + String d1 = s1.substring(s1_length - i); + String c2 = s2.substring(0, s2_length - i); + String d2 = s2.substring(s2_length - i); + + if (isScramble(a1, a2) && isScramble(b1, b2)) { + return true; + } + if (isScramble(a1, d2) && isScramble(b1, c2)) { + return true; + } + if (isScramble(d1, a2) && isScramble(c1, b2)) { + return true; + } + if (isScramble(d1, d2) && isScramble(c1, c2)) { + return true; + } + } + return false; + } + } + + public static void main(String[] args) { + String s1 = "rgeat"; + String s2 = "raegr"; + boolean result = new Q91_ScrambleString().isScramble(s1, s2); + System.out.println(result); + } + + public boolean isScrambleMy(String s1, String s2) { + int s1_len = s1.length(), s2_len = s2.length(); + if (s1.equals(s2)) { + return true; + } else if (s1_len != s2_len) { + return false; + } else if (s1_len == 1 && !s1.equals(s2)) { + return false; + } else { + for (int i = 1; i <= s1_len / 2; i++) { + String a1 = s1.substring(0, i), b1 = s1.substring(i), c1 = s1.substring(0, s1_len - i), d1 = s1.substring(s1_len - i); + String a2 = s2.substring(0, i), b2 = s2.substring(i), c2 = s2.substring(0, s1_len - i), d2 = s2.substring(s1_len - i); + if (isScrambleMy(a1, a2) && isScrambleMy(b1, b2)) { + return true; + } + if (isScrambleMy(c1, c2) && isScrambleMy(d1, d2)) { + return true; + } + if (isScrambleMy(a1, d2) && isScrambleMy(b1, c2)) { + return true; + } + if (isScrambleMy(c1, b2) && isScrambleMy(d1, a2)) { + return true; + } + } + } + return false; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q92_Search2DMatrix.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q92_Search2DMatrix.java new file mode 100644 index 0000000..13b9ccc --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q92_Search2DMatrix.java @@ -0,0 +1,30 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q92_Search2DMatrix { + + public static void main(String[] args) { + int[][] matrix = { + {1, 3, 5, 7}, + {10, 11, 16, 20}, + {23, 30, 34, 50} + }; + } + + public boolean searchMatrix(int[][] matrix, int target) { + int width = matrix[0].length, height = matrix.length; + int col = 0, row = width - 1; + while (col < height && row >= 0) { + if (matrix[col][row] == target) { + return true; + } else if (matrix[col][row] > target) { + --row; + } else { + ++col; + } + } + return false; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q93_SearchForRange.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q93_SearchForRange.java new file mode 100644 index 0000000..ce88496 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q93_SearchForRange.java @@ -0,0 +1,137 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 24, 2012 + */ +package LeetCode.OnlineJudge; + +import Util.TestUtil; + +public class Q93_SearchForRange { + + public int[] searchRange(int[] A, int target) { + int range[] = new int[2], length = A.length; + range[0] = BinarySearchLow(A, 0, length - 1, target); + range[1] = BinarySearchHigh(A, 0, length - 1, target); + return range; + } + + private int BinarySearchLow(int A[], int s, int e, int target) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + int v = A[m]; + if (v == target && (m == 0 || A[m - 1] < target)) { + return m; + } else if (v < target) { + return BinarySearchLow(A, m + 1, e, target); + } else { + return BinarySearchLow(A, s, m - 1, target); + } + } + + private int BinarySearchHigh(int A[], int s, int e, int target) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + int v = A[m]; + if (v == target && (m == e || A[m + 1] > target)) { + return m; + } else if (v > target) { + return BinarySearchHigh(A, s, m - 1, target); + } else { + return BinarySearchHigh(A, m + 1, e, target); + } + } + + public int[] searchRangeEx(int[] A, int target) { + int[] range = new int[2]; + int s = 0, length = A.length, e = length - 1, m = 0; + while (s < e) { + m = s + (e - s) / 2; + if (A[m] < target) { + s = m + 1; + } else if (A[m] > target) { + e = m - 1; + } else { + break; + } + } + if (A[m] == target) { + s = m; + e = m; + while (s >= 0 && A[s] == A[m]) { + --s; + } + if (A[m] != A[s]) { + ++s; + } + while (e < length && A[e] == A[m]) { + ++e; + } + if (A[m] != A[e]) { + --e; + } + range[0] = s; + range[1] = e; + } else { + range[0] = -1; + range[1] = -1; + } + return range; + } + + public static void main(String[] args) { + int A[] = {5, 7, 7, 8, 8, 8, 8, 8, 8, 8, 10}; + int range[] = new Q93_SearchForRange().searchRangeMy(A, 8); + System.out.println(range[0] + "," + range[1]); + int range2[] = new Q93_SearchForRange().searchRange(A, 8); + System.out.println(range2[0] + "," + range2[1]); + + int test[] = TestUtil.generateArray(99999999, 3, false); + java.util.Arrays.sort(test); + long l1 = System.currentTimeMillis(); + int testr1[] = new Q93_SearchForRange().searchRange(test, 1); + long l2 = System.currentTimeMillis(); + int testr2[] = new Q93_SearchForRange().searchRangeMy(test, 1); + long l3 = System.currentTimeMillis(); + long span1 = l2 - l1, span2 = l3 - l2; + System.out.println(testr1[0] + "," + testr1[1] + " Cost " + span1); + System.out.println(testr2[0] + "," + testr2[1] + " Cost " + span2); + } + + public int[] searchRangeMy(int[] A, int target) { + int range[] = new int[2], length = A.length; + range[0] = BinarySearchLowMy(A, 0, length - 1, target); + range[1] = BinarySearchHighMy(A, 0, length - 1, target); + return range; + } + + private int BinarySearchLowMy(int A[], int s, int e, int target) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + if (A[m] == target && (m == 0 || A[m - 1] < A[m])) { + return m; + } else if (A[m] < target) { + return BinarySearchLowMy(A, m + 1, e, target); + } else { + return BinarySearchLowMy(A, s, m - 1, target); + } + } + + private int BinarySearchHighMy(int A[], int s, int e, int target) { + if (s > e) { + return -1; + } + int m = s + (e - s) / 2; + if (A[m] == target && (m == A.length - 1 || A[m + 1] > A[m])) { + return m; + } else if (A[m] > target) { + return BinarySearchHighMy(A, s, m - 1, target); + } else { + return BinarySearchHighMy(A, m + 1, e, target); + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q94_SearchInRotatedSortedArray.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q94_SearchInRotatedSortedArray.java new file mode 100644 index 0000000..6b720a6 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q94_SearchInRotatedSortedArray.java @@ -0,0 +1,13 @@ +/** + * Sanqiang Zhao Www.131X.Com + * Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q94_SearchInRotatedSortedArray { + + //the same as Q95 + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q95_SearchInRotatedSortedArray2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q95_SearchInRotatedSortedArray2.java new file mode 100644 index 0000000..ca04952 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q95_SearchInRotatedSortedArray2.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q95_SearchInRotatedSortedArray2 { + + public static void main(String[] args) { + int[] A = {4, 4, 4, 1, 2, 3, 4, 4, 4}; + int target = 2; + boolean result = new Q95_SearchInRotatedSortedArray2().searchMy(A, target, 0, A.length-1); + System.out.println(result); + } + + public boolean searchMy(int[] A, int target, int s, int e) { + if (s > e) { + return false; + } + int m = s + (e - s) / 2; + if (A[m] == target || A[s] == target || A[e] == target) { + return true; + } + if (A[s] < A[m]) { + if (target > A[s] && target < A[m]) { + return searchMy(A, target, s, m - 1); + } else { + return searchMy(A, target, m + 1, e); + } + } else if (A[s] > A[m]) { + if (target > A[m] && target < A[e]) { + return searchMy(A, target, m + 1, e); + } else { + return searchMy(A, target, s, m - 1); + } + } else { + if (A[m] != A[e]) { + return searchMy(A, target, m + 1, e); + } else { + if (searchMy(A, target, s, m - 1)) { + return true; + } else { + return searchMy(A, target, m + 1, e); + } + } + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q96_SearchInsertPosition.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q96_SearchInsertPosition.java new file mode 100644 index 0000000..bf2180b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q96_SearchInsertPosition.java @@ -0,0 +1,45 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q96_SearchInsertPosition { + + public int searchInsert(int[] A, int target) { + int s = 0, length = A.length, e = length - 1, m; + while (s < e) { + m = s + (e - s) / 2; + if (A[m] == target) { + return m; + } else if (A[m] < target) { + s = m + 1; + } else { + e = m - 1; + } + } + return s; + } + + public static void main(String[] args) { + int A[] = {1, 3, 5, 7, 9, 11}; + int pos = new Q96_SearchInsertPosition().searchInsertMy(A, 2); + System.out.println(pos); + } + + //remind: default in the left + public int searchInsertMy(int[] A, int target) { + int s = 0, len = A.length, e = len - 1; + while (s < e) { + int m = s + (e - s) / 2; + if (A[m] == target) { + return m; + } else if (A[m] < target) { + s = m + 1; + } else { + e = m - 1; + } + } + + return s; + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q97_SetMatrixZero.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q97_SetMatrixZero.java new file mode 100644 index 0000000..68dad56 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q97_SetMatrixZero.java @@ -0,0 +1,42 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q97_SetMatrixZero { + + public static void main(String[] args) { + int[][] matrix = { + {1, 2, 3, 4}, + {5, 6, 0, 8}, + {9, 1, 2, 3} + }; + new Q97_SetMatrixZero().setZeroes(matrix); + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[0].length; j++) { + System.out.print(matrix[i][j]); + } + System.out.println(); + } + } + + public void setZeroes(int[][] matrix) { + boolean[] col = new boolean[matrix.length]; + boolean[] row = new boolean[matrix[0].length]; + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] == 0) { + col[i] = true; + row[j] = true; + } + } + } + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[0].length; j++) { + if (col[i] || row[j]) { + matrix[i][j] = 0; + } + } + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q98_SimplifyPath.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q98_SimplifyPath.java new file mode 100644 index 0000000..a4a5315 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q98_SimplifyPath.java @@ -0,0 +1,65 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +import java.util.Stack; +import java.util.Iterator; + +public class Q98_SimplifyPath { + + public String simplifyPath(String path) { + String section[] = path.split("/"); + Stack stack = new Stack<>(); + for (int i = 0; i < section.length; i++) { + if (section[i].equals("..")) { + if (!stack.isEmpty()) { + stack.pop(); + } + } else if (section[i].equals(".") || section[i].equals("")) { + } else { + stack.push(section[i]); + } + } + StringBuilder sb = new StringBuilder(); + if (stack.isEmpty()) { + sb.append("/"); + } else { + for (Iterator it = stack.iterator(); it.hasNext();) { + String item = it.next(); + sb.append("/").append(item); + } + } + return sb.toString(); + } + + public static void main(String[] args) { + String path = "/a/./b/c/"; + String path2 = new Q98_SimplifyPath().simplifyPathMy(path); + System.out.println(path2); + } + + public String simplifyPathMy(String path) { + String[] secters = path.split("/"); + Stack stack = new Stack<>(); + for (String secter : secters) { + if (secter.equals("..")) { + if (!stack.isEmpty()) { + stack.pop(); + } + } else if (secter.equals("") || secter.equals(".")) { + } else { + stack.push(secter); + } + } + StringBuilder sb = new StringBuilder(); + while (!stack.isEmpty()) { + String secter = stack.pop(); + sb.insert(0, "/" + secter); + } + if (sb.length() == 0) { + sb.append("/"); + } + return sb.toString(); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q99_SortColors.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q99_SortColors.java new file mode 100644 index 0000000..84aa188 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q99_SortColors.java @@ -0,0 +1,71 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 25, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q99_SortColors { + + public void sortColorsOneLoop(int[] A) { + int length = A.length, l = 0, r = length - 1, k = 0; + while (k <= r) { + if (A[k] == 2) { + k++; + } else if (A[k] == 1) { + swap(A, l++, k++); + } else if (A[k] == 3) { + swap(A, r--, k); + } + } + } + + private void swap(int[] A, int s, int e) { + int temp = A[s]; + A[s] = A[e]; + A[e] = temp; + } + + public void sortColorsTwoLoop(int[] A) { + int tab[] = new int[0xff]; + int i, length = A.length; + for (i = 0; i < length; ++i) { + ++tab[A[i]]; + } + int pos = 0; + for (i = 0; i < 0xff; ++i) { + while (tab[i] > 0) { + A[pos++] = i; + --tab[i]; + } + } + } + + public static void main(String[] args) { + int A[] = {1, 2, 3, 2, 3, 1, 1, 2, 3}; + new Q99_SortColors().sortColorsMy(A); + for (int i : A) { + System.out.print(i); + } + System.out.println(); + int A2[] = {1, 2, 3, 2, 3, 1, 1, 2, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1}; + new Q99_SortColors().sortColorsOneLoop(A2); + for (int i : A2) { + System.out.print(i); + } + } + + public void sortColorsMy(int[] A) { + int len = A.length, i = 0, j = 0, k = len - 1; + while (j <= k) { + if (A[j] == 1) { + swap(A, i, j); + ++i; + ++j; + } else if (A[j] == 2) { + ++j; + } else if (A[j] == 3) { + swap(A, j, k); + --k; + } + } + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q9_BestTimeBuySellStock2.java b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q9_BestTimeBuySellStock2.java new file mode 100644 index 0000000..c765f43 --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/Q9_BestTimeBuySellStock2.java @@ -0,0 +1,45 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package LeetCode.OnlineJudge; + +public class Q9_BestTimeBuySellStock2 { + + public int maxProfit(int[] prices) { + int i = 1, length = prices.length, buy_day = 0; + int MaxProfitVal = 0; + for (; i < length; ++i) { + if (prices[i] >= prices[i - 1]) { + continue; + } + MaxProfitVal += prices[i - 1] - prices[buy_day]; + buy_day = i; + } + if (prices[i - 1] > prices[buy_day]) { + MaxProfitVal += prices[i - 1] - prices[buy_day]; + } + return MaxProfitVal; + } + + //my way + public int maxProfitEx(int[] prices) { + int max = 0; + int buy_date = 0, i, length = prices.length; + for (i = 1; i < length; i++) { + if (prices[i] < prices[i - 1]) { + max += prices[i - 1] - prices[buy_date]; + buy_date = i; + } + } + max += prices[length - 1] - prices[buy_date]; + return max; + } + + public static void main(String[] args) { + int[] prices = {2, 3, 1, 2, 3, 2, 9, 10}; + int profit = new Q9_BestTimeBuySellStock2().maxProfit(prices); + System.out.println(profit); + int profit2 = new Q9_BestTimeBuySellStock2().maxProfitEx(prices); + System.out.println(profit2); + } +} diff --git a/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/newXMLDocument.xml b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/newXMLDocument.xml new file mode 100644 index 0000000..4c6c72b --- /dev/null +++ b/Algorithm-Java-Backup/src/LeetCode/OnlineJudge/newXMLDocument.xml @@ -0,0 +1,10 @@ + + + + + + 107 119 120 121 15 33 61 68 76 + diff --git a/Algorithm-Java-Backup/src/MultiThread/Common.java b/Algorithm-Java-Backup/src/MultiThread/Common.java new file mode 100644 index 0000000..e68fbec --- /dev/null +++ b/Algorithm-Java-Backup/src/MultiThread/Common.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Mar 7, 2013 + */ +package MultiThread; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Common { + + public static void main(String[] args) { + Common c = new Common(); + E1 e1 = c.new E1(); + E2 e2 = c.new E2(); + Thread t1 = new Thread(e1), t2 = new Thread(e2); + t1.start(); + t2.start(); + } + Integer x = 1, lock = 0; + + public class E1 implements Runnable { + + @Override + public void run() { + synchronized (x) { // cannot change to lock + try { + x.wait(); + } catch (InterruptedException ex) { + Logger.getLogger(Common.class.getName()).log(Level.SEVERE, null, ex); + } + for (int i = 0; i < 10; i++) { + System.out.println("Awaked"); + } + + } + } + } + + public class E2 implements Runnable { + + @Override + public void run() { + synchronized (x) { + System.out.println("Pulse!!!"); + x.notifyAll(); + System.out.println("Heihei!"); + } + } + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/DepthFirstOrder.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/DepthFirstOrder.java new file mode 100644 index 0000000..5122044 --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/DepthFirstOrder.java @@ -0,0 +1,75 @@ +/** + * Sanqiang Zhao Www.131X.Com Jul 4, 2013 + */ +package Princeton.Graphs.Directed; + +import Princeton.Graphs.Graph; +import Princeton.Graphs.GraphType; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Stack; + +public class DepthFirstOrder { + + private boolean[] marked; // marked[v] = has v been marked in dfs? + public Queue preorder; // vertices in preorder + public Queue postorder; // vertices in postorder + public Queue reverseorder; // vertices in reverse +// private int[] pre; // pre[v] = preorder number of v +// private int[] post; // post[v] = postorder number of v +// private int preCounter; // counter or preorder numbering +// private int postCounter; // counter for postorder numbering + + public DepthFirstOrder(Graph g) { +// pre = new int[g.V()]; +// post = new int[g.V()]; + postorder = new LinkedList(); + preorder = new LinkedList(); + reverseorder = new LinkedList<>(); + marked = new boolean[g.V()]; + for (int i = 0; i < g.V(); i++) { + if (!marked[i]) { + dfs(g, i); + } + } + reverse(); + } + + public void dfs(Graph g, int v) { + marked[v] = true; + preorder.add(v); + for (Integer adj : g.adj(v)) { + if (!marked[adj]) { + dfs(g, adj); + } + } + postorder.add(v); + } + + public void reverse() { + Stack reverse = new Stack(); + for (int v : postorder) { + reverse.push(v); + } + while (!reverse.isEmpty()) { + reverseorder.add(reverse.pop()); + } + } + + public static void main(String[] args) { + Graph g = new Graph(6, GraphType.Directed); + g.addEdge(0, 1).addEdge(2, 3).addEdge(3, 4).addEdge(4, 5).addEdge(0, 2).addEdge(2, 4).addEdge(3, 5).addEdge(2, 1); + DepthFirstOrder dfo = new DepthFirstOrder(g); + for (Integer i : dfo.preorder) { + System.out.print(i + " "); + } + System.out.println(); + for (Integer i : dfo.postorder) { + System.out.print(i + " "); + } + System.out.println(); + for (Integer i : dfo.reverseorder) { + System.out.print(i + " "); + } + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/DirectedCycle.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/DirectedCycle.java new file mode 100644 index 0000000..adf51b3 --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/DirectedCycle.java @@ -0,0 +1,57 @@ +/** + * Sanqiang Zhao Www.131X.Com Jul 4, 2013 + */ +package Princeton.Graphs.Directed; + +import Princeton.Graphs.Graph; +import Princeton.Graphs.GraphType; +import java.util.Stack; + +public class DirectedCycle { + + int[] pathTo; + boolean[] marked; + boolean[] onStacked; + + public DirectedCycle(Graph g) { + marked = new boolean[g.V()]; + onStacked = new boolean[g.V()]; + pathTo = new int[g.V()]; + for (int i = 0; i < g.V(); i++) { + if (!marked[i]) { + dfs(g, i); + } + } + } + + public void dfs(Graph g, int v) { + marked[v] = true; + onStacked[v] = true; + for (int adj : g.adj(v)) { + if (!marked[adj]) { + pathTo[v] = adj; + dfs(g, adj); + } else if (onStacked[adj]) { + Stack s = new Stack<>(); + int loop = adj; + s.push(adj); + loop = pathTo[loop]; + while (loop != adj) { + s.push(loop); + loop = pathTo[loop]; + } + for (Integer step : s) { + System.out.println(step); + } + return; + } + } + onStacked[v] = false; + } + + public static void main(String[] args) { + Graph g = new Graph(3, GraphType.Directed); + g.addEdge(0, 1).addEdge(1, 2).addEdge(2, 0); + DirectedCycle dc = new DirectedCycle(g); + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/KosarajuSharirSCC.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/KosarajuSharirSCC.java new file mode 100644 index 0000000..2da12ad --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/KosarajuSharirSCC.java @@ -0,0 +1,43 @@ +/** + * Sanqiang Zhao Www.131X.Com Jul 5, 2013 + */ +package Princeton.Graphs.Directed; + +import Princeton.Graphs.Graph; +import Princeton.Graphs.GraphType; + +public class KosarajuSharirSCC { + + private boolean[] marked; // marked[v] = has vertex v been visited? + private int[] id; // id[v] = id of strong component containing v + private int count; // number of strongly-connected components + + public KosarajuSharirSCC(Graph g) { + DepthFirstOrder dfo = new DepthFirstOrder(g.reverse()); + marked = new boolean[g.V()]; + id = new int[g.V()]; + for (int v : dfo.reverseorder) { + if (!marked[v]) { + dfs(g, v); + count++; + } + } + } + + private void dfs(Graph g, int v) { + marked[v] = true; + id[v] = count; + for (int w : g.adj(v)) { + if (!marked[w]) { + dfs(g, w); + } + } + } + + public static void main(String[] args) { + Graph g = new Graph(4, GraphType.Directed); + g.addEdge(0,1).addEdge(1, 2).addEdge(2, 3).addEdge(3, 0); + KosarajuSharirSCC ks = new KosarajuSharirSCC(g); + System.out.println(ks.count); + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/TransitiveClosure.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/TransitiveClosure.java new file mode 100644 index 0000000..967e77f --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Directed/TransitiveClosure.java @@ -0,0 +1,12 @@ +/** + * Sanqiang Zhao Www.131X.Com Jul 5, 2013 + */ +package Princeton.Graphs.Directed; + +public class TransitiveClosure { + + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Edge.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Edge.java new file mode 100644 index 0000000..e559b41 --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Edge.java @@ -0,0 +1,29 @@ +/** + * Sanqiang Zhao Www.131X.Com Jul 5, 2013 + */ +package Princeton.Graphs; + +public class Edge implements Comparable { + + public int v; + public int w; + public double weight; + + public Edge(int v, int w, double weight) + { + this.v = v; + this.w = w; + this.weight = weight; + } + + @Override + public int compareTo(Edge t) { + if (this.weight > t.weight) { + return 1; + } else if (this.weight < t.weight) { + return -1; + } else { + return 0; + } + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Graph.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Graph.java new file mode 100644 index 0000000..1c6c2f3 --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Graph.java @@ -0,0 +1,136 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package Princeton.Graphs; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * + * @author szhao + */ +public class Graph { + + private GraphType Type; + private int V; + private int E; + private ArrayList[] adj; + private ArrayList[] adjw; + + public Graph(int v, GraphType type) { + this.E = 0; + this.V = v; + this.Type = type; + if (type.equals(Type.Weighted)) { + this.adjw = new ArrayList[v]; + for (int i = 0; i < v; i++) { + adj[i] = new ArrayList<>(); + } + } else { + this.adj = new ArrayList[v]; + for (int i = 0; i < v; i++) { + adj[i] = new ArrayList<>(); + } + } + } + + public Graph reverse() { + Graph g_r = new Graph(this.V, this.Type); + for (int i = 0; i < adj.length; i++) { + ArrayList list = adj[i]; + for (Integer w : list) { + g_r.addEdge(w, i); + } + } + return g_r; + } + + public int V() { + return V; + } + + public int E() { + return E; + } + + public Graph addEdge(int v, int w) { + ++E; + if (Type == GraphType.Directed) { + adj[v].add(w); + } else if (Type == GraphType.Undirected) { + adj[v].add(w); + adj[w].add(v); + } + return this; + } + + public Graph addEdge(int v, int w, double weight) { + ++E; + if (Type == GraphType.Weighted) { + adjw[v].add(new Edge(v, w, weight)); + adjw[w].add(new Edge(w, v, weight)); + } + return this; + } + + public ArrayList adj(int v) { + return adj[v]; + } + + public Iterator getReverseEdgeIterator(int v) { + if (Type == GraphType.Undirected) { + throw new UnsupportedOperationException(); + } + return new ReverseEdgeIterator(v); + } + + private class ReverseEdgeIterator implements Iterable, Iterator { + + public ReverseEdgeIterator(int v) { + this.currentV = v; + } + int currentV = 0, loopV = 0; + + @Override + public Iterator iterator() { + return this; + } + + @Override + public boolean hasNext() { + while (loopV < V) { + if (adj[loopV].contains(currentV)) { + return true; + } + loopV++; + } + return false; + } + + @Override + public Integer next() { + if (hasNext()) { + return loopV++; + } else { + throw new NoSuchElementException(); + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Not supported yet."); + } + } + + public static void main(String[] args) { + Graph g = new Graph(5, GraphType.Directed); + g.addEdge(0, 1).addEdge(0, 2).addEdge(0, 3).addEdge(0, 4).addEdge(2, 1); + Iterator it = g.getReverseEdgeIterator(1); + while (it.hasNext()) { + System.out.println(it.next()); + } + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/GraphType.java b/Algorithm-Java-Backup/src/Princeton/Graphs/GraphType.java new file mode 100644 index 0000000..025df4c --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/GraphType.java @@ -0,0 +1,9 @@ +/** + * Sanqiang Zhao Www.131X.Com Jul 4, 2013 + */ +package Princeton.Graphs; + +public enum GraphType { + + Directed, Undirected, Weighted +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/MinimumSpanningTree/MinPQ.java b/Algorithm-Java-Backup/src/Princeton/Graphs/MinimumSpanningTree/MinPQ.java new file mode 100644 index 0000000..9145273 --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/MinimumSpanningTree/MinPQ.java @@ -0,0 +1,120 @@ +package Princeton.Graphs.MinimumSpanningTree; + +import java.util.Iterator; + +public class MinPQ { + + private K[] pq; + int n; // n means index n+1 means num + + public K min() { + return pq[0]; + } + + public MinPQ(int capability) { + pq = (K[]) new Object[capability]; + n = -1; + } + + public void insert(K v) { + pq[++n] = v; + if (n + 1 >= pq.length - 1) { + increaseCapacity(); + } + swim(n); + } + + public K delMin() { + K min = pq[0]; + exch(0, n--); + sink(0); + if (n < pq.length / 4) { + decreaseCapacity(); + } + return min; + } + + private void increaseCapacity() { + K[] n_pq = (K[]) new Object[pq.length * 2]; + for (int i = 0; i <= n; i++) { + n_pq[i] = pq[i]; + } + pq = n_pq; + } + + private void decreaseCapacity() { + K[] n_pq = (K[]) new Object[pq.length / 2]; + for (int i = 0; i <= n; i++) { + n_pq[i] = pq[i]; + } + pq = n_pq; + } + + private void sink(int k) { + while (k * 2 <= n) { + int child = 2 * k + 1; + if (child + 1 <= n && smaller(child + 1, child)) { + ++child; + } + if (smaller(child, k)) { + exch(k, child); + k = child; + } else { + break; + } + } + + } + + private void swim(int k) { + while (k > 0 && k / 2 < k) { + int parent = (k - 1) / 2; + if (smaller(k, parent)) { + exch(parent, k); + } else { + break; + } + } + } + + private boolean greater(K a, K b) { + return ((Comparable) a).compareTo(b) > 0; + } + + private boolean smaller(int a, int b) { + return ((Comparable) pq[a]).compareTo(pq[b]) < 0; + } + + private boolean greater(int a, int b) { + return ((Comparable) pq[a]).compareTo(pq[b]) > 0; + } + + private void exch(int a, int b) { + K temp = pq[a]; + pq[a] = pq[b]; + pq[b] = temp; + } + + public static void main(String[] args) { + MinPQ mp = new MinPQ(1); + mp.insert(3); + System.out.println(mp.min()); + mp.insert(2); + System.out.println(mp.min()); + mp.insert(1); + System.out.println(mp.min()); + mp.insert(11); + System.out.println(mp.min()); + mp.insert(12); + System.out.println(mp.min()); + mp.insert(13); + System.out.println(mp.min()); + mp.insert(14); + System.out.println(mp.min()); + mp.insert(15); + System.out.println(mp.min()); + System.out.println(mp.delMin()); + System.out.println(mp.delMin()); + System.out.println(mp.delMin()); + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Undirected/Biconnected.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Undirected/Biconnected.java new file mode 100644 index 0000000..d603299 --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Undirected/Biconnected.java @@ -0,0 +1,67 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package Princeton.Graphs.Undirected; + +import Princeton.Graphs.Graph; +import Princeton.Graphs.GraphType; +import java.sql.PreparedStatement; +import java.util.Iterator; +import javax.naming.BinaryRefAddr; + +/** + * + * @author szhao + */ +public class Biconnected { + + int[] pre, id; + int count; + + public Biconnected(Graph g) { + count = 0; + id = new int[g.V()]; + for (int i = 0; i < g.V(); i++) { + id[i] = -1; + } + pre = new int[g.V()]; + for (int i = 0; i < g.V(); i++) { + pre[i] = -1; + } + for (int i = 0; i < g.V(); i++) { + if (pre[i] == -1) { + dfs(g, i, i); + } + } + } + + private void dfs(Graph g, int v, int u) { + int children = 0; + id[v] = count++; + pre[v] = id[v]; + for (int w : g.adj(v)) { + if (pre[w] == -1) { + ++children; + dfs(g, w, v); + pre[v] = Math.min(pre[v], pre[w]); + if (pre[w] >= id[v] && u != v) { + System.out.println(v); + } + } else if (w != u) { + pre[v] = Math.min(pre[v], id[w]); + } + } + + if (u == v && children > 0) { + System.out.println(u); + } + + } + + public static void main(String[] args) { + Graph g = new Graph(4, GraphType.Undirected); + g.addEdge(0, 1).addEdge(1, 2).addEdge(0, 2).addEdge(0, 3); + Biconnected bc = new Biconnected(g); + } +} diff --git a/Algorithm-Java-Backup/src/Princeton/Graphs/Undirected/Bridge.java b/Algorithm-Java-Backup/src/Princeton/Graphs/Undirected/Bridge.java new file mode 100644 index 0000000..95f58fa --- /dev/null +++ b/Algorithm-Java-Backup/src/Princeton/Graphs/Undirected/Bridge.java @@ -0,0 +1,57 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package Princeton.Graphs.Undirected; + +import Princeton.Graphs.Graph; +import Princeton.Graphs.GraphType; + +/** + * + * @author szhao + */ +public class Bridge { + + int[] id, pre; + int count; + + public Bridge(Graph g) { + count = 0; + id = new int[g.V()]; + for (int i = 0; i < g.V(); i++) { + id[i] = -1; + } + pre = new int[g.V()]; + for (int i = 0; i < g.V(); i++) { + pre[i] = -1; + } + for (int i = 0; i < g.V(); i++) { + if (pre[i] == -1) { + dfs(g, i, i); + } + } + } + + private void dfs(Graph g, int v, int u) { + id[v] = count++; + pre[v] = id[v]; + for (int w : g.adj(v)) { + if (pre[w] == -1) { + dfs(g, w, v); + pre[v] = Math.min(pre[v], pre[w]); + if (pre[w] == id[w]) { + System.out.println(v + "-" + w); + } + } else if (w != u) { + pre[v] = Math.min(pre[v], id[w]); + } + } + } + + public static void main(String[] args) { + Graph g = new Graph(3, GraphType.Undirected); + g.addEdge(0, 1).addEdge(1, 2).addEdge(0, 2); + Bridge b = new Bridge(g); + } +} diff --git a/Algorithm-Java-Backup/src/Util/BinaryTreeNode.java b/Algorithm-Java-Backup/src/Util/BinaryTreeNode.java new file mode 100644 index 0000000..0d57261 --- /dev/null +++ b/Algorithm-Java-Backup/src/Util/BinaryTreeNode.java @@ -0,0 +1,126 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package Util; + +public class BinaryTreeNode { + + public T Data; + public BinaryTreeNode Left; + public BinaryTreeNode Right; + public BinaryTreeNode Parent; //Optional + + public BinaryTreeNode(T _data) { + this.Data = _data; + this.Left = null; + this.Right = null; + } + + public BinaryTreeNode(T _data, BinaryTreeNode _left, BinaryTreeNode _right) { + this.Data = _data; + this.Left = _left; + this.Right = _right; + _left = this; + _right = this; + } + + public BinaryTreeNode(T _data, BinaryTreeNode _left, BinaryTreeNode _right, BinaryTreeNode _parent) { + this.Data = _data; + this.Left = _left; + this.Right = _right; + _left = this; + _right = this; + this.Parent = _parent; + } + + public int getHeight() { + return getHeightHelper(this); + } + + private int getHeightHelper(BinaryTreeNode node) { + if (node == null) { + return 0; + } + int l = getHeightHelper(node.Left); + int r = getHeightHelper(node.Right); + return Math.max(l, r) + 1; + } + + public static BinaryTreeNode getSampleTree() { + BinaryTreeNode btn2 = new BinaryTreeNode(2); + BinaryTreeNode btn7 = new BinaryTreeNode(7); + BinaryTreeNode btn5 = new BinaryTreeNode(5, btn2, btn7); + BinaryTreeNode btn12 = new BinaryTreeNode(12); + BinaryTreeNode btn17 = new BinaryTreeNode(17); + BinaryTreeNode btn15 = new BinaryTreeNode(15, btn12, btn17); + BinaryTreeNode btn10 = new BinaryTreeNode(10, btn5, btn15); + return btn10; + } + + public static BinaryTreeNode getSampleTree2() { + BinaryTreeNode btn2 = new BinaryTreeNode(3); + BinaryTreeNode btn7 = new BinaryTreeNode(3); + BinaryTreeNode btn5 = new BinaryTreeNode(2, btn2, btn7); + BinaryTreeNode btn12 = new BinaryTreeNode(4); + BinaryTreeNode btn17 = new BinaryTreeNode(4); + BinaryTreeNode btn15 = new BinaryTreeNode(2, btn12, btn17); + BinaryTreeNode btn10 = new BinaryTreeNode(1, btn5, btn15); + return btn10; + } + + public static BinaryTreeNode getSampleTree3() { + BinaryTreeNode btn2 = new BinaryTreeNode(3); + BinaryTreeNode btn5 = new BinaryTreeNode(2, btn2, null); + BinaryTreeNode btn10 = new BinaryTreeNode(1, btn5, null); + return btn10; + } + + public static BinaryTreeNode getSampleTree4() { + BinaryTreeNode btn2 = new BinaryTreeNode(10); + BinaryTreeNode btn7 = new BinaryTreeNode(10); + BinaryTreeNode btn5 = new BinaryTreeNode(10, btn2, btn7); + BinaryTreeNode btn12 = new BinaryTreeNode(12); + BinaryTreeNode btn17 = new BinaryTreeNode(17); + BinaryTreeNode btn15 = new BinaryTreeNode(15, btn12, btn17); + BinaryTreeNode btn10 = new BinaryTreeNode(10, btn5, btn15); + return btn10; + } + + public static BinaryTreeNode getCharSampleTree() { + BinaryTreeNode btn2 = new BinaryTreeNode('1'); + BinaryTreeNode btn7 = new BinaryTreeNode('2'); + BinaryTreeNode btn5 = new BinaryTreeNode('+', btn2, btn7); + BinaryTreeNode btn12 = new BinaryTreeNode('4'); + BinaryTreeNode btn17 = new BinaryTreeNode('3'); + BinaryTreeNode btn15 = new BinaryTreeNode('+', btn12, btn17); + BinaryTreeNode btn10 = new BinaryTreeNode('*', btn5, btn15); + return btn10; + } + + public static BinaryTreeNode getSampleTree5() { + BinaryTreeNode btn2 = new BinaryTreeNode(10); + BinaryTreeNode btn7 = new BinaryTreeNode(10); + BinaryTreeNode btn5 = new BinaryTreeNode(10, btn2, btn7); + BinaryTreeNode btn12 = new BinaryTreeNode(12); + BinaryTreeNode btn17 = new BinaryTreeNode(17); + BinaryTreeNode btn15 = new BinaryTreeNode(15, btn12, btn17); + BinaryTreeNode btn10 = new BinaryTreeNode(10, btn5, btn15); + btn2.Left = new BinaryTreeNode(1); + //btn7.Left = new BinaryTreeNode(1); + return btn10; + } + + private static void ReverseOrder(BinaryTreeNode root) { + if (root == null) { + return; + } + ReverseOrder(root.Right); + System.out.println(root.Data); + ReverseOrder(root.Left); + } + + public static void main(String[] args) { + BinaryTreeNode sample = getSampleTree(); + ReverseOrder(sample); + } +} diff --git a/Algorithm-Java-Backup/src/Util/Dic.java b/Algorithm-Java-Backup/src/Util/Dic.java new file mode 100644 index 0000000..960b0eb --- /dev/null +++ b/Algorithm-Java-Backup/src/Util/Dic.java @@ -0,0 +1,36 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 11, 2013 + */ +package Util; + +import java.util.ArrayList; + +public class Dic { + + public ArrayList getDic(int num_len, int char_len) { + ArrayList[] solutions = new ArrayList[2]; + solutions[0] = new ArrayList<>(); + solutions[1] = new ArrayList<>(); + int i = 0; + for (; i <= 9; i++) { + solutions[0].add(String.valueOf(i)); + } + i = 1; + for (; i < num_len; i++) { + ArrayList pre = solutions[(i + 1) % 2]; + ArrayList cur = solutions[i % 2]; + cur.clear(); + int len = pre.size(); + for (int j = 0; j < len; j++) { + String str = pre.get(j); + for (int num = 1; num <= 9; num++) { + cur.add(str + num); + } + } + } + return solutions[1]; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/Util/GraphNode.java b/Algorithm-Java-Backup/src/Util/GraphNode.java new file mode 100644 index 0000000..ea3fbd2 --- /dev/null +++ b/Algorithm-Java-Backup/src/Util/GraphNode.java @@ -0,0 +1,47 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 4, 2013 + */ +package Util; + +import java.util.ArrayList; + +public class GraphNode { + + public V Data; + public ArrayList> Nodes; + public short state; + + public GraphNode(V _data) { + this.Data = _data; + this.Nodes = new ArrayList<>(); + } + + public void add(V val) { + GraphNode node = new GraphNode<>(val); + add(node); + } + + public void add(GraphNode node) { + Nodes.add(node); + } + + public static GraphNode getSampleGraphNode() + { + GraphNode n1 = new GraphNode<>(1); + n1.add(2); + n1.add(3); + n1.Nodes.get(0).add(n1); + return n1; + } + + public static GraphNode getSampleGraphNode2() + { + GraphNode n1 = new GraphNode<>(1); + n1.add(2); + n1.add(3); + return n1; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/Util/LinkedListNode.java b/Algorithm-Java-Backup/src/Util/LinkedListNode.java new file mode 100644 index 0000000..9f60bdd --- /dev/null +++ b/Algorithm-Java-Backup/src/Util/LinkedListNode.java @@ -0,0 +1,129 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 18, 2012 + */ +package Util; + +public class LinkedListNode { + + public V Data; + public LinkedListNode Next; + + public LinkedListNode(V _data) { + this.Data = _data; + this.Next = null; + } + + public LinkedListNode(V _data, LinkedListNode _last) { + this.Data = _data; + _last.Next = this; + } + + public int getLength() { + int count = 0; + LinkedListNode runner = this; + while (runner != null) { + ++count; + runner = runner.Next; + } + return count; + } + + public void print() { + LinkedListNode runner = this; + while (runner != null) { + System.out.println(runner.Data); + runner = runner.Next; + } + System.out.println(); + } + + /*public LinkedListNode(V _data, LinkedListNode _next) { + this.Data = _data; + this.Next = _next; + } */ + public static LinkedListNode getSampleLinkedList() { + LinkedListNode n1 = new LinkedListNode<>(2); + LinkedListNode n2 = new LinkedListNode<>(5, n1); + LinkedListNode n3 = new LinkedListNode<>(7, n2); + LinkedListNode n4 = new LinkedListNode<>(10, n3); + LinkedListNode n5 = new LinkedListNode<>(12, n4); + LinkedListNode n6 = new LinkedListNode<>(15, n5); + LinkedListNode n7 = new LinkedListNode<>(17, n6); + return n1; + } + + public static LinkedListNode getSampleLinkedList2() { + LinkedListNode n1 = new LinkedListNode<>(1); + LinkedListNode n2 = new LinkedListNode<>(2, n1); + LinkedListNode n3 = new LinkedListNode<>(3, n2); + LinkedListNode n4 = new LinkedListNode<>(4, n3); + LinkedListNode n5 = new LinkedListNode<>(5, n4); + LinkedListNode n6 = new LinkedListNode<>(6, n5); + LinkedListNode n7 = new LinkedListNode<>(7, n6); + LinkedListNode n8 = new LinkedListNode<>(8, n7); + return n1; + } + + public static LinkedListNode getSampleLinkedList3() { + LinkedListNode n1 = new LinkedListNode<>(11); + LinkedListNode n2 = new LinkedListNode<>(12, n1); + LinkedListNode n3 = new LinkedListNode<>(13, n2); + LinkedListNode n4 = new LinkedListNode<>(14, n3); + LinkedListNode n5 = new LinkedListNode<>(15, n4); + LinkedListNode n6 = new LinkedListNode<>(16, n5); + LinkedListNode n7 = new LinkedListNode<>(17, n6); + return n1; + } + + public static LinkedListNode getSampleLinkedList4() { + LinkedListNode n1 = new LinkedListNode<>(0); + LinkedListNode n2 = new LinkedListNode<>(0, n1); + LinkedListNode n3 = new LinkedListNode<>(1, n2); + LinkedListNode n4 = new LinkedListNode<>(2, n3); + LinkedListNode n5 = new LinkedListNode<>(2, n4); + LinkedListNode n6 = new LinkedListNode<>(2, n5); + LinkedListNode n7 = new LinkedListNode<>(3, n6); + return n1; + } + + public static LinkedListNode getSampleLinkedList5() { + LinkedListNode n1 = new LinkedListNode<>(0); + LinkedListNode n2 = new LinkedListNode<>(1, n1); + LinkedListNode n3 = new LinkedListNode<>(3, n2); + LinkedListNode n4 = new LinkedListNode<>(5, n3); + LinkedListNode n5 = new LinkedListNode<>(2, n4); + LinkedListNode n6 = new LinkedListNode<>(4, n5); + LinkedListNode n7 = new LinkedListNode<>(6, n6); + return n1; + } + + public static LinkedListNode getSampleLinkedList6() { + LinkedListNode n1 = new LinkedListNode<>(0); + LinkedListNode n2 = new LinkedListNode<>(1, n1); + LinkedListNode n3 = new LinkedListNode<>(2, n2); + LinkedListNode n4 = new LinkedListNode<>(3, n3); + LinkedListNode n5 = new LinkedListNode<>(4, n4); + LinkedListNode n6 = new LinkedListNode<>(5, n5); + LinkedListNode n7 = new LinkedListNode<>(6, n6); + LinkedListNode n8 = new LinkedListNode<>(7, n7); + n8.Next = n3; + return n1; + } + + public static LinkedListNode getSampleLinkedList7() { + LinkedListNode n1 = new LinkedListNode<>(0); + LinkedListNode n2 = new LinkedListNode<>(1, n1); + LinkedListNode n3 = new LinkedListNode<>(2, n2); + LinkedListNode n4 = new LinkedListNode<>(3, n3); + LinkedListNode n5 = new LinkedListNode<>(3, n4); + LinkedListNode n6 = new LinkedListNode<>(2, n5); + LinkedListNode n7 = new LinkedListNode<>(1, n6); + LinkedListNode n8 = new LinkedListNode<>(0, n7); + return n1; + } + + public static void main(String[] args) { + LinkedListNode n = getSampleLinkedList(); + + } +} diff --git a/Algorithm-Java-Backup/src/Util/TestUtil.java b/Algorithm-Java-Backup/src/Util/TestUtil.java new file mode 100644 index 0000000..4d0f28e --- /dev/null +++ b/Algorithm-Java-Backup/src/Util/TestUtil.java @@ -0,0 +1,60 @@ +/** + * Sanqiang Zhao Www.131X.Com Dec 17, 2012 + */ +package Util; + +import java.util.Calendar; +import java.util.Random; + +public class TestUtil { + + public static Integer[] intToInteger(int[] arr) + { + Integer[] trans = new Integer[arr.length]; + for (int i = 0; i < arr.length; i++) { + trans[i] = arr[i]; + } + return trans; + } + + public static int[] generateArray(int n) { + return generateArray(n, 100, true); + } + + public static int[] generateArray(int n, int max, boolean negative) { + int[] arr = new int[n]; + Random r = new Random(Calendar.getInstance().MILLISECOND); + for (int i = 0; i < n; i++) { + int current = r.nextInt(max); + if (negative) { + current -= max / 2; + } + arr[i] = current; + } + return arr; + } + + public static String generateArrayString(int n, int max) { + int[] arr = generateArray(n, max, false); + StringBuilder sb = new StringBuilder(); + for (int num : arr) { + sb.append(num); + } + return sb.toString(); + } + + public static int[][] generateMatrix(int height, int width, int max) { + int matrix[][] = new int[height][width]; + Random r = new Random(Calendar.getInstance().MILLISECOND); + for (int i = 0; i < height; ++i) { + for (int j = 0; j < width; ++j) { + matrix[i][j] = r.nextInt(max); + } + } + return matrix; + } + + public static void main(String[] args) { + System.out.println(generateArrayString(100, 10)); + } +} diff --git a/Algorithm-Java/src/algorithm/java/AlgorithmJava.java b/Algorithm-Java-Backup/src/algorithm/java/AlgorithmJava.java similarity index 100% rename from Algorithm-Java/src/algorithm/java/AlgorithmJava.java rename to Algorithm-Java-Backup/src/algorithm/java/AlgorithmJava.java diff --git a/Algorithm-Java-Backup/src/haimenboy/Q10_Palindrome.java b/Algorithm-Java-Backup/src/haimenboy/Q10_Palindrome.java new file mode 100644 index 0000000..60776fd --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q10_Palindrome.java @@ -0,0 +1,34 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q10_Palindrome { + + public boolean verify(String in) { + char[] arr = in.toCharArray(); + for (int i = 0; i < arr.length / 2; i++) { + if (arr[i] != arr[arr.length - 1 - i]) { + return false; + } + } + return true; + } + + public boolean verifyRotate(String in) { + for (int i = 0; i < in.length(); i++) { + String left = in.substring(0, i); + String right = in.substring(i); + if (verify(right + left)) { + return true; + } + } + return false; + } + + public static void main(String[] args) { + Q10_Palindrome q10 = new Q10_Palindrome(); + System.out.println(q10.verify("12241")); + System.out.println(q10.verifyRotate("21123")); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q11_PrintSubsets.java b/Algorithm-Java-Backup/src/haimenboy/Q11_PrintSubsets.java new file mode 100644 index 0000000..674dd72 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q11_PrintSubsets.java @@ -0,0 +1,94 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q11_PrintSubsets { + + void print(char[] list) { + for (int i = 0; i <= list.length; i++) { + boolean[] checkers = new boolean[list.length]; + print(list, checkers, 0, i); + } + } + + void print(char[] list, boolean[] checkers, int start, int remaining) { + if (remaining == 0) { + StringBuilder sb = new StringBuilder(); + sb.append("["); + for (int i = 0; i < checkers.length; i++) { + if (checkers[i]) { + sb.append(list[i]).append(","); + } + } + sb.append("]"); + System.out.println(sb.toString()); + } else { + if (start + remaining > list.length) { + } else { + for (int i = start; i < list.length; i++) { + if (!checkers[i]) { + checkers[i] = true; + print(list, checkers, i + 1, remaining - 1); + checkers[i] = false; + } + } + } + } + + } + + public static void main(String[] args) { + String text = "abc"; + new Q11_PrintSubsets().print(text.toCharArray()); + + int[] nums = {1, 2, 3}; + PrintSubSet(nums); + } + //step 1, decide how many elements in a sub-array to be printed + + public static void PrintSubSet(int[] nums) { + //now we process the first step + for (int i = 0; i <= nums.length; i++)//subset length could vary from 0 to nums.length + { + boolean[] ifPrint = new boolean[nums.length]; + PrintSubSet(nums, ifPrint, 0, i);//start from 0th index, and the size varies for the loop + } + } + + //step 2, this method processed the action to print out all possible combination of elements with fixed size + //as we discussed in the slide, we need three additional variables to keep track of status + //boolean array to know whether printed out or not, + //start is the start index to be printed to prevent duplicates + //remain is keeping track of how many remaining elements to be processed for the subset action + public static void PrintSubSet(int[] nums, boolean[] ifPrint, int start, int remain) { + //firstly if remain==0, we done! + if (remain == 0) { + System.out.print("{"); + //check each ifPrint status to decide print or not + for (int i = 0; i < ifPrint.length; i++) { + if (ifPrint[i]) { + System.out.print(nums[i] + ","); + } + } + System.out.print("}\n");//format the output of one subset one line + } else { + //now is the key recursive part, we need process char by char from the start position until end + //before that, we need determine whether we proceed or not to check if start+remain>nums.length + if (start + remain > nums.length)//not possible even if all remaining element to be used + ; else { + for (int i = start; i < nums.length; i++) { + //now before we come to recursive part we have to make sure this position is not used + if (!ifPrint[i]) { + //now assign its value to true as used indicator + ifPrint[i] = true; + //recursive call! + PrintSubSet(nums, ifPrint, i + 1, remain - 1);//notice the update of start index and remain count + //another key point! set the position back to false and proceed from next element + ifPrint[i] = false; + } + } + } + } + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q12_MergeArray.java b/Algorithm-Java-Backup/src/haimenboy/Q12_MergeArray.java new file mode 100644 index 0000000..47ae705 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q12_MergeArray.java @@ -0,0 +1,11 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q12_MergeArray { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q13_2Sum.java b/Algorithm-Java-Backup/src/haimenboy/Q13_2Sum.java new file mode 100644 index 0000000..846467d --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q13_2Sum.java @@ -0,0 +1,28 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q13_2Sum { + + void printSum(int[] nums, int target) { + int s = 0, e = nums.length - 1; + while (s < e) { + if (nums[s] + nums[e] == target) { + System.out.println(nums[s] + "+" + nums[e]); + ++s; + --e; + } else if (nums[s] + nums[e] > target) { + --e; + } else { + ++s; + } + } + } + + public static void main(String[] args) { + int[] nums = {1,2,3,4,5,6,6,7,8,9,10}; + int target = 12; + new Q13_2Sum().printSum(nums, 12); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q14_PrintCoinComb.java b/Algorithm-Java-Backup/src/haimenboy/Q14_PrintCoinComb.java new file mode 100644 index 0000000..ea46585 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q14_PrintCoinComb.java @@ -0,0 +1,31 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q14_PrintCoinComb { + + void printCoinComb(int[] coin, int[] count, int cur, int remaing) { + if (cur == coin.length) { + if (remaing == 0) { + for (int i = 0; i < count.length; i++) { + if (count[i] > 0) { + System.out.print(coin[i] + "=" + count[i] + " , "); + } + } + System.out.println(); + } + } else { + for (int i = 0; remaing - i * coin[cur] >= 0; i++) { + count[cur] = i; + printCoinComb(coin, count, cur + 1, remaing - i * coin[cur]); + } + } + } + + public static void main(String[] args) { + int[] coin = {5, 2, 1}; + int remaing = 20; + new Q14_PrintCoinComb().printCoinComb(coin, new int[coin.length], 0, remaing); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q15_ClosestInBST.java b/Algorithm-Java-Backup/src/haimenboy/Q15_ClosestInBST.java new file mode 100644 index 0000000..410dd03 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q15_ClosestInBST.java @@ -0,0 +1,41 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +import Util.BinaryTreeNode; + +public class Q15_ClosestInBST { + + int find(BinaryTreeNode head, int target) { + return target + findHelper(head, target); + } + + int findHelper(BinaryTreeNode head, int target) { + if (head == null) { + return Integer.MAX_VALUE; + } + if (head.Data < target) { + return smaller(head.Data - target, findHelper(head.Right, target)); + } else if (head.Data > target) { + return smaller(head.Data - target, findHelper(head.Left, target)); + } else { + return 0; + } + } + + int smaller(int a, int b) { + if (Math.abs(a) > Math.abs(b)) { + return b; + } else { + return a; + } + } + + public static void main(String[] args) { + Q15_ClosestInBST q15 = new Q15_ClosestInBST(); + BinaryTreeNode head = BinaryTreeNode.getSampleTree(); + int val = q15.find(head, 9); + System.out.println(val); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q16_LargestSubSum.java b/Algorithm-Java-Backup/src/haimenboy/Q16_LargestSubSum.java new file mode 100644 index 0000000..909d553 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q16_LargestSubSum.java @@ -0,0 +1,11 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q16_LargestSubSum { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q17_Division.java b/Algorithm-Java-Backup/src/haimenboy/Q17_Division.java new file mode 100644 index 0000000..8faa640 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q17_Division.java @@ -0,0 +1,27 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +public class Q17_Division { + + int divison(int divident, int divisor) { + if (divident == divisor) { + return 1; + } else if (divident < divisor) { + return 0; + } + int count = 1; + while (divident - (count << 1) * divisor >= 0) { + count <<= 1; + } + return divison(divident - count * divisor, divisor) + count; + } + + public static void main(String[] args) { + int divident = 12345678; + int divisor = 4321; + int result = new Q17_Division().divison(divident, divisor); + System.out.print(result); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q18_CountRotation.java b/Algorithm-Java-Backup/src/haimenboy/Q18_CountRotation.java new file mode 100644 index 0000000..e4f6313 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q18_CountRotation.java @@ -0,0 +1,63 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 25, 2013 + */ +package haimenboy; + +public class Q18_CountRotation { + + int find(int[] nums) { + int s = 0, e = nums.length - 1; + while (s < e) { + if (nums[s] < nums[e]) { + return e + 1; + } + int m = s + (e - s) / 2; + if (nums[s] <= nums[m] && nums[m + 1] <= nums[e] && nums[s] >= nums[e]) { + return m + 1; + } else if (nums[s] <= nums[m]) { + s = m + 1; + } else { + e = m - 1; + } + } + return -1; + } + + public static void main(String[] args) { + int[] nums = {8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7}; + int pos = new Q18_CountRotation().find(nums); + System.out.println(pos); + System.out.println(FindRotation(nums)); + } + + public static int FindRotation(int[] rotates) { + //as we discussed in slides, the key is to use a binary-search similar way to fast-find rotation place + int start = 0; + int end = rotates.length - 1;//basically you can imagine we use a recursion-similar way but use loop to process + + //now the key for keep processing is before start index meets our end index + while (start < end) { + //as we say the other criterial to determine stopping the process is the sub-array is sorted! + if (rotates[start] < rotates[end])//e.g. {1,2,3,4,5} + { + return end + 1;//notice end is the key position for output the rotation, and in our case, the length-5 array rotates by 5, thus it is equal to itself + } else { + //binary-search based key process + int mid = (start + end) / 2; + //ok now we check if the perfect cut-point is found + //what is perfect cut-point? Think about {3,4,5,1,2} and we choose 5 then {3,4} and {1,2} are sorted!, thus we rotated by 3 + if (rotates[start] <= rotates[mid] && rotates[mid + 1] <= rotates[end]) { + return mid + 1;//here it is mid position we want to output, however, plus one is because index starts with 0 + } else if (rotates[start] <= rotates[mid])//if left half is sorted, thus the key is keep process in right half + { + start = mid + 1;//similar as binary search to shrink the focus window + } else//need keep track of left sub-array + { + end = mid - 1; + } + } + } + //the system should already print out index in the loop, if coming here return an error + return -1; + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q19_MatrixSpiral.java b/Algorithm-Java-Backup/src/haimenboy/Q19_MatrixSpiral.java new file mode 100644 index 0000000..64a9801 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q19_MatrixSpiral.java @@ -0,0 +1,76 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 25, 2013 + */ +package haimenboy; + +public class Q19_MatrixSpiral { + + void print(int[][] matrix, int col, int row, int width, int height) { + if (col == matrix.length || row == matrix[0].length) { + return; + } + for (int i = 0; i < width; i++) { + System.out.print(matrix[col][row + i] + " "); + } + for (int i = 1; i < height; i++) { + System.out.print(matrix[col + i][row + width - 1] + " "); + } + if (height > 1) { + for (int i = 1; i < width; i++) { + System.out.print(matrix[col + height - 1][row + width - 1 - i] + " "); + } + } + if (width > 1) { + for (int i = 1; i < height - 1; i++) { + System.out.print(matrix[col + height - 1 - i][row] + " "); + } + } + + print(matrix, col + 1, row + 1, width - 2, height - 2); + } + + void print(int[][] matrix) { + int col = 0, row = -1, i = 0, len = 0; + while (true) { + if (i % 2 == 0) { + len = matrix[0].length - i / 2; + } else { + len = matrix.length - i / 2 - 1; + } + if (len == 0) { + return; + } + int xd = 0, yd = 0; + switch (i % 4) { + case 0: + xd = 1; + break; + case 1: + yd = 1; + break; + case 2: + xd = -1; + break; + case 3: + yd = -1; + break; + } + for (int pos = 0; pos < len; pos++) { + System.out.print(matrix[col + (1 + pos) * yd][row + (1 + pos) * xd] + " "); + } + col += len * yd; + row += len * xd; + ++i; + } + } + + public static void main(String[] args) { + int[][] matrix = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12} + }; + //new Q19_MatrixSpiral().print(matrix, 0, 0, matrix[0].length, matrix.length); + new Q19_MatrixSpiral().print(matrix); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q1_ReverseLinkedlist.java b/Algorithm-Java-Backup/src/haimenboy/Q1_ReverseLinkedlist.java new file mode 100644 index 0000000..1b9c0c2 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q1_ReverseLinkedlist.java @@ -0,0 +1,49 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +import Util.LinkedListNode; + +public class Q1_ReverseLinkedlist { + + LinkedListNode new_head = null; + + LinkedListNode reverse(LinkedListNode head) { + new_head = null; + reverseRC(head); + head.Next = null; + return new_head; + } + + LinkedListNode reverseRC(LinkedListNode head) { + if (head.Next == null || head == null) { + new_head = head; + return head; + } + LinkedListNode node = reverseRC(head.Next); + node.Next = head; + return head; + } + + LinkedListNode reverseSample(LinkedListNode head) { + if (head.Next == null || head == null) { + return head; + } + LinkedListNode remaining = reverseSample(head.Next); + LinkedListNode cur = remaining; + while (cur.Next != null) { + cur = cur.Next; + } + cur.Next = head; + head.Next = null; + return remaining; + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList(); + head.print(); + LinkedListNode reverse = new Q1_ReverseLinkedlist().reverse(head); + reverse.print(); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q20_SearchMatrix.java b/Algorithm-Java-Backup/src/haimenboy/Q20_SearchMatrix.java new file mode 100644 index 0000000..f1f12be --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q20_SearchMatrix.java @@ -0,0 +1,11 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 26, 2013 + */ +package haimenboy; + +public class Q20_SearchMatrix { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q21_Queue2Stack.java b/Algorithm-Java-Backup/src/haimenboy/Q21_Queue2Stack.java new file mode 100644 index 0000000..ef90dd8 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q21_Queue2Stack.java @@ -0,0 +1,11 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 26, 2013 + */ +package haimenboy; + +public class Q21_Queue2Stack { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q22_ArithmeticTreeExp.java b/Algorithm-Java-Backup/src/haimenboy/Q22_ArithmeticTreeExp.java new file mode 100644 index 0000000..5342062 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q22_ArithmeticTreeExp.java @@ -0,0 +1,53 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 26, 2013 + */ +package haimenboy; + +import Util.BinaryTreeNode; +import java.util.Stack; + +public class Q22_ArithmeticTreeExp { + + Stack stack = new Stack<>(); + + void compute(BinaryTreeNode head) { + if (head == null) { + return; + } + compute(head.Left); + compute(head.Right); + int r, l; + switch (head.Data) { + case '+': + r = stack.pop() - '0'; + l = stack.pop() - '0'; + stack.push((char) ((l + r) + '0')); + break; + case '-': + r = stack.pop() - '0'; + l = stack.pop() - '0'; + stack.push((char) ((l - r) + '0')); + break; + case '*': + r = stack.pop() - '0'; + l = stack.pop() - '0'; + stack.push((char) ((l * r) + '0')); + break; + case '/': + r = stack.pop() - '0'; + l = stack.pop() - '0'; + stack.push((char) ((l / r) + '0')); + break; + default: + stack.push(head.Data); + break; + } + } + + public static void main(String[] args) { + Q22_ArithmeticTreeExp q22 = new Q22_ArithmeticTreeExp(); + q22.compute(BinaryTreeNode.getCharSampleTree()); + char c = q22.stack.pop(); + System.out.println(c - '0'); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q23_MaxSubMatrix.java b/Algorithm-Java-Backup/src/haimenboy/Q23_MaxSubMatrix.java new file mode 100644 index 0000000..94b9736 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q23_MaxSubMatrix.java @@ -0,0 +1,49 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 26, 2013 + */ +package haimenboy; + +public class Q23_MaxSubMatrix { + + int max(int[][] matrix) { + int max = 0; + for (int col_s = 0; col_s < matrix.length; col_s++) { + for (int col_e = col_s; col_e < matrix.length; col_e++) { + int[] temp = new int[matrix[0].length]; + for (int row = 0; row < matrix[0].length; row++) { + int sum = 0; + for (int col = col_s; col <= col_e; col++) { + sum += matrix[col][row]; + } + temp[row] = sum; + } + int cur_max = max(temp); + max = Math.max(max, cur_max); + } + } + return max; + } + + int max(int[] arr) { + int max = 0, sum = 0; + for (int i = 0; i < arr.length; i++) { + sum += arr[i]; + if (sum > 0) { + max = Math.max(max, sum); + } else { + sum = 0; + } + } + return max; + } + + public static void main(String[] args) { + int[][] matrix = { + {1, 2, 0, 3}, + {2, 1, -9, -9}, + {1, -10, -90, -100} + }; + int max = new Q23_MaxSubMatrix().max(matrix); + System.out.println(max); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q24_BalancePoint.java b/Algorithm-Java-Backup/src/haimenboy/Q24_BalancePoint.java new file mode 100644 index 0000000..b8edf9d --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q24_BalancePoint.java @@ -0,0 +1,34 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 26, 2013 + */ +package haimenboy; + +public class Q24_BalancePoint { + + int getPoint(int[] arr) { + int[] left = new int[arr.length]; + int[] right = new int[arr.length]; + int sum = 0; + for (int i = 0; i < arr.length; i++) { + sum += arr[i]; + left[i] = sum; + } + sum = 0; + for (int i = arr.length - 1; i >= 0; i--) { + sum += arr[i]; + right[i] = sum; + } + for (int i = 1; i < arr.length - 1; i++) { + if (left[i - 1] == right[i + 1]) { + return i; + } + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {1, 2, 9, -1, 4}; + int point = new Q24_BalancePoint().getPoint(arr); + System.out.println(point); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q25_MidLinkList.java b/Algorithm-Java-Backup/src/haimenboy/Q25_MidLinkList.java new file mode 100644 index 0000000..d7fa4e2 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q25_MidLinkList.java @@ -0,0 +1,28 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 27, 2013 + */ +package haimenboy; + +import Util.LinkedListNode; + +public class Q25_MidLinkList { + + int len = 0; + int cur = 0; + + void getMid(LinkedListNode head) { + if (head != null) { + ++len; + getMid(head.Next); + ++cur; + } + if (cur * 2 == len || cur * 2 == len + 1) { + System.out.println(head.Data); + } + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList(); + new Q25_MidLinkList().getMid(head); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q26_LongestPalidrome.java b/Algorithm-Java-Backup/src/haimenboy/Q26_LongestPalidrome.java new file mode 100644 index 0000000..e85d023 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q26_LongestPalidrome.java @@ -0,0 +1,58 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 27, 2013 + */ +package haimenboy; + +public class Q26_LongestPalidrome { + + String longest(String input) { + int len = input.length(), max_len = 0, max_start = 0, cur_len = 0; + for (int mid = 0; mid < len; mid++) { + int l = mid - 1; + int r = mid + 1; + while (l >= 0 && r < len) { + if (input.charAt(l) != input.charAt(r)) { + cur_len = r - l + 1; + if (cur_len > max_len) { + max_len = cur_len - 2; + max_start = l + 1; + } + break; + } + --l; + ++r; + } + cur_len = r - l + 1; + if (cur_len > max_len) { + max_len = cur_len - 2; + max_start = l + 1; + } + l = mid; + r = mid + 1; + while (l >= 0 && r < len) { + if (input.charAt(l) != input.charAt(r)) { + cur_len = r - l + 1; + if (cur_len > max_len) { + max_len = cur_len - 2; + max_start = l + 1; + } + break; + } + cur_len = r - l + 1; + if (cur_len > max_len) { + max_len = cur_len - 2; + max_start = l + 1; + } + --l; + ++r; + } + } + return input.substring(max_start, max_start + max_len); + } + + public static void main(String[] args) { + String input = "EGHGABCBAEE"; + String output = new Q26_LongestPalidrome().longest(input); + System.out.println(output); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q27_RotateLinklist.java b/Algorithm-Java-Backup/src/haimenboy/Q27_RotateLinklist.java new file mode 100644 index 0000000..607f393 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q27_RotateLinklist.java @@ -0,0 +1,31 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 27, 2013 + */ +package haimenboy; + +import Util.LinkedListNode; + +public class Q27_RotateLinklist { + + LinkedListNode rotate(LinkedListNode head, int k) { + LinkedListNode new_end = null, new_start = null, runner = head; + for (int i = 0; i < k - 1; i++) { + runner = runner.Next; + } + new_end = runner; + new_start = new_end.Next; + while (runner.Next != null) { + runner = runner.Next; + } + runner.Next = head; + new_end.Next = null; + return new_start; + } + + public static void main(String[] args) { + LinkedListNode head = LinkedListNode.getSampleLinkedList(); + head.print(); + LinkedListNode new_head = new Q27_RotateLinklist().rotate(head, 2); + new_head.print(); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q28_IntersectLinklist.java b/Algorithm-Java-Backup/src/haimenboy/Q28_IntersectLinklist.java new file mode 100644 index 0000000..f10ed5d --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q28_IntersectLinklist.java @@ -0,0 +1,10 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 27, 2013 + */ +package haimenboy; + +public class Q28_IntersectLinklist { + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q29_CountWays.java b/Algorithm-Java-Backup/src/haimenboy/Q29_CountWays.java new file mode 100644 index 0000000..535442a --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q29_CountWays.java @@ -0,0 +1,29 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 27, 2013 + */ +package haimenboy; + +public class Q29_CountWays { + + int count(int n) { + if (n == 1) { + return 1; + } else if (n == 2) { + return 2; + } else if (n == 3) { + return 4; + } + int[] tab = {1, 2, 4}; + if (n-- > 3) { + int ways = tab[0] + tab[1] + tab[2]; + tab[0] = tab[1]; + tab[1] = tab[2]; + tab[2] = ways; + } + + return tab[2]; + } + + public static void main(String[] args) { + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q2_Sqrt.java b/Algorithm-Java-Backup/src/haimenboy/Q2_Sqrt.java new file mode 100644 index 0000000..6205740 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q2_Sqrt.java @@ -0,0 +1,36 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +public class Q2_Sqrt { + + final double precision = 0.000001; + + public double sqrt(double num) { + if (num < 0) { + return -1; + } else if (num == 0 || num == 1) { + return num; + } + double s = 0, e = num; + while (e - s > precision) { + double m = s + (e - s) / 2; + double sqaure = m * m; + if (sqaure == num) { + return m; + } else if (sqaure > num) { + e = m; + } else { + s = m; + } + } + return s; + } + + public static void main(String[] args) { + double num = 3; + double sqpt = new Q2_Sqrt().sqrt(num); + System.out.println(sqpt); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q30_SudokuSolver.java b/Algorithm-Java-Backup/src/haimenboy/Q30_SudokuSolver.java new file mode 100644 index 0000000..62b3f36 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q30_SudokuSolver.java @@ -0,0 +1,90 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 27, 2013 + */ +package haimenboy; + +public class Q30_SudokuSolver { + + public boolean solveSudoku(int[][] board) { + for (int col = 0; col < board.length; col++) { + for (int row = 0; row < board[0].length; row++) { + if (board[col][row] == 0) { + for (int num = 1; num <= 9; num++) { + board[col][row] = num; + if (solve(board, col, row)) { + if (solveSudoku(board)) { + return true; + } + } + board[col][row] = 0; + } + return false; + } + } + } + return true; + } + + private boolean solve(int[][] board, int col, int row) { + boolean[] check = new boolean[9]; + for (int i = 0; i < board.length; i++) { + int val = board[i][row] - 1; + if (val == -1) { + continue; + } + if (check[val]) { + return false; + } else { + check[val] = true; + } + } + check = new boolean[9]; + for (int i = 0; i < board[0].length; i++) { + int val = board[col][i] - 1; + if (val == -1) { + continue; + } + if (check[val]) { + return false; + } else { + check[val] = true; + } + } + check = new boolean[9]; + for (int y = col / 3 * 3; y < col / 3 * 3 + 3; y++) { + for (int x = row / 3 * 3; x < row / 3 * 3 + 3; x++) { + int val = board[y][x] - 1; + if (val == -1) { + continue; + } + if (check[val]) { + return false; + } else { + check[val] = true; + } + } + } + return true; + } + + public static void main(String[] args) { + int[][] board = { + {5, 3, 0, 0, 7, 0, 0, 0, 0}, + {6, 0, 0, 1, 9, 5, 0, 0, 0}, + {0, 9, 8, 0, 0, 0, 0, 6, 0}, + {8, 0, 0, 0, 6, 0, 0, 0, 3}, + {4, 0, 0, 8, 0, 3, 0, 0, 1}, + {7, 0, 0, 0, 2, 0, 0, 0, 6}, + {0, 6, 0, 0, 0, 0, 2, 8, 0}, + {0, 0, 0, 4, 1, 9, 0, 0, 5}, + {0, 0, 0, 0, 8, 0, 0, 7, 9} + }; + new Q30_SudokuSolver().solveSudoku(board); + for (int y = 0; y < board.length; y++) { + for (int x = 0; x < board[0].length; x++) { + System.out.print(board[y][x] + " "); + } + System.out.println(); + } + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q3_CountSame.java b/Algorithm-Java-Backup/src/haimenboy/Q3_CountSame.java new file mode 100644 index 0000000..996eda0 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q3_CountSame.java @@ -0,0 +1,52 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +import Util.BinaryTreeNode; + +public class Q3_CountSame { + + public int countSameInSortedArray(int[] nums, int target, int s, int e) { + if (e < s) { + return 0; + } else if (nums[s] > target) { + return 0; + } else if (nums[e] < target) { + return 0; + } else if (nums[s] == target && nums[e] == target) { + return e - s + 1; + } + int m = s + (e - s) / 2; + if (nums[m] == target) { + return 1 + countSameInSortedArray(nums, target, s, m - 1) + countSameInSortedArray(nums, target, m + 1, e); + } else if (nums[m] > target) { + return countSameInSortedArray(nums, target, s, m - 1); + } else { + return countSameInSortedArray(nums, target, m + 1, e); + } + } + + public int countSameInBST(BinaryTreeNode head, int target) { + if (head == null) { + return 0; + } + if (head.Data == target) { + return 1 + countSameInBST(head.Left, target) + countSameInBST(head.Right, target); + } else if (head.Data > target) { + return countSameInBST(head.Right, target); + } else { + return countSameInBST(head.Left, target); + } + } + + public static void main(String[] args) { + Q3_CountSame q3 = new Q3_CountSame(); + int[] nums = {1, 2, 3, 3, 3, 3, 3, 4}; + int count1 = q3.countSameInSortedArray(nums, 3, 0, nums.length-1); + System.out.println(count1); + BinaryTreeNode head = BinaryTreeNode.getSampleTree4(); + int count2 = q3.countSameInBST(head, 10); + System.out.println(count2); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q4_PrintParenthesis.java b/Algorithm-Java-Backup/src/haimenboy/Q4_PrintParenthesis.java new file mode 100644 index 0000000..a63f82e --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q4_PrintParenthesis.java @@ -0,0 +1,11 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +public class Q4_PrintParenthesis { + + public static void main(String[] args) { + + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q5_ConvertToRational.java b/Algorithm-Java-Backup/src/haimenboy/Q5_ConvertToRational.java new file mode 100644 index 0000000..0f22d12 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q5_ConvertToRational.java @@ -0,0 +1,39 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +public class Q5_ConvertToRational { + + String convert(double num) { + StringBuilder sb = new StringBuilder(); + double divisor, divident = 1; + while (true) { + divisor = divident * num; + if (divisor - (int) divisor == 0) { + break; + } + divident *= 10; + } + int gcd = GCD((int) divident, (int) divisor);; + sb.append((int)divisor / gcd).append("/").append((int)divident / gcd); + return sb.toString(); + } + + int GCD(int a, int b) { + if (a < b) { + return GCD(b, a); + } + int rem = a % b; + if (rem == 0) { + return b; + } + return GCD(b, rem); + } + + public static void main(String[] args) { + double num = 0.124234; + String rational = new Q5_ConvertToRational().convert(num); + System.out.println(rational); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q6_PrintPermutate.java b/Algorithm-Java-Backup/src/haimenboy/Q6_PrintPermutate.java new file mode 100644 index 0000000..be5da5d --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q6_PrintPermutate.java @@ -0,0 +1,70 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +public class Q6_PrintPermutate { + + void print(char[] list, int cur) { + if (cur == list.length - 1) { + System.out.println(new String(list)); + return; + } + print(list, cur + 1); + for (int i = cur + 1; i < list.length; i++) { + swap(list, i, cur); + print(list, cur + 1); + swap(list, cur, i); + } + } + + void swap(char[] list, int i, int j) { + char temp = list[i]; + list[i] = list[j]; + list[j] = temp; + } + + public static void main(String[] args) { + String text = "123"; + new Q6_PrintPermutate().print(text.toCharArray(), 0); + //PrintPermutation(text.toCharArray(), 0); + } + + //Sample + public static void PrintPermutation(char[] inputs, int currentFocus) { + //before start, check if currentFocus comes to the last char + if (currentFocus == inputs.length - 1) { + System.out.println(new String(inputs)); + return; + } + + //now firstly keep the current char order in the array and proceed to next + PrintPermutation(inputs, currentFocus + 1); + + //now need swap each next char with currentFocus + for (int i = currentFocus + 1; i < inputs.length; i++) { + //swap the char pair of position (currentFocus, i) + //in order to remove the duplicates, the key is to check if the two char unequal before swapping! + boolean ifAppear = false; + for (int j = 0; j < i; j++) { + if (inputs[j] == inputs[i]) { + ifAppear = true; + break; + } + } + + if (ifAppear) { + continue; + } + Swap(inputs, currentFocus, i); + PrintPermutation(inputs, currentFocus + 1); + Swap(inputs, currentFocus, i); + } + } + + private static void Swap(char[] inputs, int a, int b) { + char temp = inputs[a]; + inputs[a] = inputs[b]; + inputs[b] = temp; + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q7_FindFirstOccur.java b/Algorithm-Java-Backup/src/haimenboy/Q7_FindFirstOccur.java new file mode 100644 index 0000000..9758781 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q7_FindFirstOccur.java @@ -0,0 +1,50 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 23, 2013 + */ +package haimenboy; + +public class Q7_FindFirstOccur { + + public int find(int[] nums, int target) { + int s = 0, e = nums.length - 1; + while (s < e) { + int m = s + (e - s) / 2; + if (nums[m] == target && (m == 0 || (m - 1 >= 0 && nums[m - 1] != nums[m]))) { + return m; + } else if (nums[m] < target) { + s = m + 1; + } else { + e = m - 1; + } + } + return s; + } + + public int findSample(int[] nums, int target, int s, int e) { + if (nums[s] > target) { + return -1; + } else if (nums[e] < target) { + return -1; + } + if (nums[s] == target) { + return s; + } + int m = s + (e - s) / 2; + if (nums[m] == target) { + int pos = findSample(nums, target, s, m - 1); + return pos != -1 ? pos : m; + } else if (nums[m] > target) { + return findSample(nums, target, s, m - 1); + } else { + return findSample(nums, target, m + 1, e); + } + } + + public static void main(String[] args) { + int[] nums = {1, 2, 2, 2, 3, 3, 3}; + int pos = new Q7_FindFirstOccur().find(nums, 3); + System.out.println(pos); + int pos2 = new Q7_FindFirstOccur().findSample(nums, 3, 0, nums.length - 1); + System.out.println(pos2); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q8_VerifyBST.java b/Algorithm-Java-Backup/src/haimenboy/Q8_VerifyBST.java new file mode 100644 index 0000000..1b7e6a4 --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q8_VerifyBST.java @@ -0,0 +1,26 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +import Util.BinaryTreeNode; + +public class Q8_VerifyBST { + + public boolean verify(BinaryTreeNode head, int min, int max) { + if (head == null) { + return true; + } + if (head.Data <= max && head.Data >= min) { + return verify(head.Left, min, head.Data) && verify(head.Right, head.Data, max); + } else { + return false; + } + } + + public static void main(String[] args) { + BinaryTreeNode root = BinaryTreeNode.getSampleTree(); + boolean reuslt = new Q8_VerifyBST().verify(root, Integer.MIN_VALUE, Integer.MAX_VALUE); + System.out.println(reuslt); + } +} diff --git a/Algorithm-Java-Backup/src/haimenboy/Q9_PrintTreeByLevel.java b/Algorithm-Java-Backup/src/haimenboy/Q9_PrintTreeByLevel.java new file mode 100644 index 0000000..0f89e8e --- /dev/null +++ b/Algorithm-Java-Backup/src/haimenboy/Q9_PrintTreeByLevel.java @@ -0,0 +1,53 @@ +/** + * Sanqiang Zhao Www.131X.Com Jan 24, 2013 + */ +package haimenboy; + +import Util.BinaryTreeNode; +import java.util.LinkedList; +import java.util.Queue; + +public class Q9_PrintTreeByLevel { + + public void printQueue(BinaryTreeNode head, int desire) { + Queue> nodes = new LinkedList<>(); + Queue levels = new LinkedList<>(); + if (head != null) { + nodes.add(head); + levels.add(0); + } + while (!nodes.isEmpty()) { + BinaryTreeNode node = nodes.poll(); + int level = levels.poll(); + if (level == desire) { + System.out.println(node.Data); + } + if (node.Left != null) { + nodes.add(node.Left); + levels.add(level + 1); + } + if (node.Right != null) { + nodes.add(node.Right); + levels.add(level + 1); + } + } + } + + public void printRC(BinaryTreeNode head, int desire, int level) { + if (head == null) { + return; + } + if (desire == level) { + System.out.println(head.Data); + } + printRC(head.Left, desire, level+1); + printRC(head.Right, desire, level+1); + } + + public static void main(String[] args) { + Q9_PrintTreeByLevel q9 = new Q9_PrintTreeByLevel(); + BinaryTreeNode head = BinaryTreeNode.getSampleTree(); + q9.printQueue(head, 2); + q9.printRC(head, 2, 0); + } +} diff --git a/Algorithm-Java/.DS_Store b/Algorithm-Java/.DS_Store index 888b442..7fd3c97 100644 Binary files a/Algorithm-Java/.DS_Store and b/Algorithm-Java/.DS_Store differ diff --git a/Algorithm-Java/.classpath b/Algorithm-Java/.classpath new file mode 100644 index 0000000..b4c59f7 --- /dev/null +++ b/Algorithm-Java/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/Algorithm-Java/.gitignore b/Algorithm-Java/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/Algorithm-Java/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/Algorithm-Java/.project b/Algorithm-Java/.project new file mode 100644 index 0000000..fe04b39 --- /dev/null +++ b/Algorithm-Java/.project @@ -0,0 +1,17 @@ + + + Algorithm-Java + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/Algorithm-Java/.settings/org.eclipse.jdt.core.prefs b/Algorithm-Java/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..d17b672 --- /dev/null +++ b/Algorithm-Java/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/Algorithm-Java/src/.DS_Store b/Algorithm-Java/src/.DS_Store index 3f67fe3..644691f 100644 Binary files a/Algorithm-Java/src/.DS_Store and b/Algorithm-Java/src/.DS_Store differ diff --git a/Algorithm-Java/src/Lintcode/Base/L1/CombinationSum.java b/Algorithm-Java/src/Lintcode/Base/L1/CombinationSum.java new file mode 100644 index 0000000..d012483 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/CombinationSum.java @@ -0,0 +1,52 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array; + +public class CombinationSum { + /** + * @param candidates: + * A list of integers + * @param target:An + * integer + * @return: A list of lists of integers + */ + public List> combinationSum(int[] candidates, int target) { + List> results = new ArrayList<>(); + Arrays.sort(candidates); + dfs(results, new ArrayList(), 0, target, candidates); + return results; + } + + void dfs(List> results, ArrayList result, int pos, int target, int[] candidates) { + if (target == 0) { + results.add(new ArrayList<>(result)); + } else if (target < 0) { + return; + } + + for (int i = pos; i < candidates.length; i++) { + if (i >= 1 && candidates[i - 1] == candidates[i]) { + continue; + } + + for (int cnt = 1; cnt <= target / candidates[i]; cnt++) { + for (int temp_cnt = 0; temp_cnt < cnt; temp_cnt++) { + result.add(candidates[i]); + } + dfs(results, result, i + 1, target - cnt * candidates[i], candidates); + for (int temp_cnt = 0; temp_cnt < cnt; temp_cnt++) { + result.remove(result.size() - 1); + } + } + } + } + + public static void main(String[] args) { + int[] candidates = { 2,3,4 }; + new CombinationSum().combinationSum(candidates, 5); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L1/Combine.java b/Algorithm-Java/src/Lintcode/Base/L1/Combine.java new file mode 100644 index 0000000..401b7f7 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/Combine.java @@ -0,0 +1,32 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.List; + +public class Combine { + /** + * @param n: + * Given the range of numbers + * @param k: + * Given the numbers of combinations + * @return: All the combinations of k numbers out of 1..n + */ + public List> combine(int n, int k) { + List> results = new ArrayList<>(); + dfs(results, new ArrayList(), n, k, 1); + return results; + } + + void dfs(List> results, ArrayList result, int n, int k, int idx) { + if (result.size() == k) { + results.add(new ArrayList<>(result)); + return; + } + + for (int i = idx; i <= n; i++) { + result.add(i); + dfs(results, result, n, k, 1 + i); + result.remove(result.size() - 1); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L1/LetterCombinations.java b/Algorithm-Java/src/Lintcode/Base/L1/LetterCombinations.java new file mode 100644 index 0000000..52f5cca --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/LetterCombinations.java @@ -0,0 +1,57 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.HashMap; + +public class LetterCombinations { + /** + * @param digits + * A digital string + * @return all posible letter combinations + */ + public ArrayList letterCombinations(String digits) { + ArrayList results = new ArrayList<>(); + if (digits == null || digits.length() == 0) { + return results; + } + + HashMap map = new HashMap<>(); + map.put('2', "abc"); + map.put('3', "def"); + map.put('4', "ghi"); + map.put('5', "jkl"); + map.put('6', "mno"); + map.put('7', "pqrs"); + map.put('8', "tuv"); + map.put('9', "wxyz"); + + dfs(map, results, new StringBuilder(), digits, 0); + + return results; + } + + void dfs(HashMap map, ArrayList results, StringBuilder result, String digits, int pos) { + if (pos == digits.length()) { + results.add(result.toString()); + return; + } + + + char ch = digits.charAt(pos); + if (map.containsKey(ch)) { + String chars = map.get(ch); + for (int i = 0; i < chars.length(); i++) { + result.append(chars.charAt(i)); + dfs(map, results, result, digits, 1 + pos); + result.deleteCharAt(result.length() - 1); + } + } + } + + public static void main(String[] args) { + ArrayList results = new LetterCombinations().letterCombinations("52"); + for (String result : results) { + System.out.println(result); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L1/Partition.java b/Algorithm-Java/src/Lintcode/Base/L1/Partition.java new file mode 100644 index 0000000..406a95d --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/Partition.java @@ -0,0 +1,49 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.List; + +public class Partition { + /** + * @param s: + * A string + * @return: A list of lists of string + */ + public List> partition(String s) { + List> results = new ArrayList<>(); + if (s == null || s.length() == 0) { + return results; + } + dfs(results, new ArrayList(), 0, s); + return results; + } + + void dfs(List> results, ArrayList result, int pos, String s) { + if (pos == s.length()) { + results.add(new ArrayList<>(result)); + return; + } + + for (int i = pos; i < s.length(); i++) { + String str = s.substring(pos, 1 + i); + if (isValidPalindrome(str)) { + result.add(str); + dfs(results, result, i + 1, s); + result.remove(result.size() - 1); + } + } + } + + boolean isValidPalindrome(String str) { + int left = 0, right = str.length() - 1; + while (left < right) { + if (str.charAt(left) != str.charAt(right)) { + return false; + } else { + ++left; + --right; + } + } + return true; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L1/Permute.java b/Algorithm-Java/src/Lintcode/Base/L1/Permute.java new file mode 100644 index 0000000..f2eda6e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/Permute.java @@ -0,0 +1,75 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Permute { + /** + * @param nums: + * A list of integers. + * @return: A list of permutations. + */ + public List> permute(int[] nums) { + List> results = new ArrayList<>(); + if (nums == null) { + return results; + } + Arrays.sort(nums); + boolean[] visited = new boolean[nums.length]; + dfs(results, new ArrayList(), nums, visited); + return results; + } + + void dfs(List> results, ArrayList result, int[] nums, boolean[] visited) { + if (result.size() == nums.length) { + results.add(new ArrayList<>(result)); + return; + } + + for (int i = 0; i < nums.length; i++) { + if (visited[i]) { + continue; + } + result.add(nums[i]); + visited[i] = true; + dfs(results, result, nums, visited); + result.remove(result.size() - 1); + visited[i] = false; + } + } + + /** + * @param nums: + * A list of integers. + * @return: A list of unique permutations. + */ + public List> permuteUnique(int[] nums) { + List> results = new ArrayList<>(); + if (nums == null) { + return results; + } + Arrays.sort(nums); + boolean[] visited = new boolean[nums.length]; + dfs2(results, new ArrayList(), visited, nums); + return results; + } + + void dfs2(List> results, ArrayList result,boolean[] visited, int[] nums) { + if (result.size() == nums.length) { + results.add(new ArrayList<>(result)); + return; + } + + for (int i = 0; i < nums.length; i++) { + if ((i >= 1 && nums[i - 1] == nums[i] && !visited[i - 1]) || visited[i]) { + continue; + } + result.add(nums[i]); + visited[i] = true; + dfs2(results, result, visited, nums); + result.remove(result.size() - 1); + visited[i] = false; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L1/RestoreIpAddresses.java b/Algorithm-Java/src/Lintcode/Base/L1/RestoreIpAddresses.java new file mode 100644 index 0000000..71221a6 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/RestoreIpAddresses.java @@ -0,0 +1,68 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.List; + +public class RestoreIpAddresses { + public ArrayList restoreIpAddresses(String s) { + ArrayList results = new ArrayList<>(); + if (s == null || s.length() == 0) { + return results; + } + dfs(results, new ArrayList(), 0, s, 0); + return results; + } + + void dfs(ArrayList results, ArrayList result, int pos, String s, int cnt_dot) { + if (cnt_dot == 4 && pos == s.length()) { + StringBuilder sBuilder = new StringBuilder(); + for (String ip : result) { + sBuilder.append(ip).append("."); + } + sBuilder.deleteCharAt(sBuilder.length() - 1); + results.add(sBuilder.toString()); + return; + }else if (cnt_dot > 4) { + return; + } + + for (int i = pos; i < s.length(); i++) { + String str = s.substring(pos, 1 + i); + if (isValidIp(str)) { + result.add(str); + dfs(results, result, 1 + i, s, cnt_dot + 1); + result.remove(result.size() - 1); + } + } + } + + boolean isValidIp(String str) { + if (str.length() > 3 || str.length() == 0) { + return false; + } else if (str.length() == 1 && str.charAt(0) >= '0' && str.charAt(0) <= '9') { + return true; + } else if (str.length() == 2 && str.charAt(0) >= '1' && str.charAt(0) <= '9' && str.charAt(1) >= '0' + && str.charAt(1) <= '9') { + return true; + } else if (str.length() == 3) { + if (str.charAt(0) == '1' && str.charAt(1) >= '0' && str.charAt(1) <= '9' && str.charAt(2) >= '0' + && str.charAt(2) <= '9') { + return true; + } else if (str.charAt(0) == '2' && str.charAt(1) >= '0' && str.charAt(1) <= '5' && str.charAt(2) >= '0' + && str.charAt(2) <= '5') { + return true; + } else { + return false; + } + } else { + return false; + } + } + + public static void main(String[] args) { + List results = new RestoreIpAddresses().restoreIpAddresses("101023"); + for (String result : results) { + System.out.println(result); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L1/Subsets.java b/Algorithm-Java/src/Lintcode/Base/L1/Subsets.java new file mode 100644 index 0000000..cbe019c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L1/Subsets.java @@ -0,0 +1,62 @@ +package Lintcode.Base.L1; + +import java.util.ArrayList; +import java.util.Arrays; + +public class Subsets { + /** + * @param S: + * A set of numbers. + * @return: A list of lists. All valid subsets. + */ + public ArrayList> subsets(int[] nums) { + ArrayList> results = new ArrayList<>(); + if (nums == null || nums.length == 0) { + return results; + } + Arrays.sort(nums); + dfs(results, new ArrayList(), 0, nums); + return results; + } + + void dfs(ArrayList> results, ArrayList result, int idx, int[] nums) { + results.add(new ArrayList<>(result)); + + for (int i = idx; i < nums.length; i++) { + result.add(nums[i]); + int result_size = result.size(); + dfs(results, result, i + 1, nums); + result.remove(result_size - 1); + } + } + + /** + * @param nums: + * A set of numbers. + * @return: A list of lists. All valid subsets. + */ + public ArrayList> subsetsWithDup(int[] nums) { + ArrayList> results = new ArrayList<>(); + if (nums == null || nums.length == 0) { + return results; + } + Arrays.sort(nums); + dfs2(results, new ArrayList(), 0, nums); + return results; + } + + void dfs2(ArrayList> results, ArrayList result, int idx, int[] nums) { + results.add(new ArrayList<>(result)); + + for (int i = idx; i < nums.length; i++) { + if (i >= 1 && nums[i - 1] == nums[i] && i > idx) { + continue; + } + result.add(nums[i]); + int result_size = result.size(); + dfs2(results, result, i + 1, nums); + result.remove(result_size - 1); + } + } + +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/FindFirstBadVersion.java b/Algorithm-Java/src/Lintcode/Base/L2/FindFirstBadVersion.java new file mode 100644 index 0000000..b25d708 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/FindFirstBadVersion.java @@ -0,0 +1,38 @@ +package Lintcode.Base.L2; + +public class FindFirstBadVersion { + static class SVNRepo { + public static boolean isBadVersion(int k) { + return true; + } + } + + /** + * @param n: + * An integers. + * @return: An integer which is the first bad version. + */ + public int findFirstBadVersion(int n) { + if (n <= 1) { + return 1; + } + int left = 1, right = n; + + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (SVNRepo.isBadVersion(mid)) { + right = mid; + } else { + left = mid; + } + } + + if (SVNRepo.isBadVersion(right) && !SVNRepo.isBadVersion(left)) { + return right; + } else if (SVNRepo.isBadVersion(right) && SVNRepo.isBadVersion(left)) { + return left; + } else { + return left; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/FindMin.java b/Algorithm-Java/src/Lintcode/Base/L2/FindMin.java new file mode 100644 index 0000000..f14b296 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/FindMin.java @@ -0,0 +1,51 @@ +package Lintcode.Base.L2; + +public class FindMin { + /** + * @param nums: + * a rotated sorted array + * @return: the minimum number in the array + */ + public int findMin(int[] nums) { + if (nums == null || nums.length == 0) { + return -1; + } + + int left = 0, right = nums.length - 1, target = nums[nums.length - 1]; + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (nums[mid] > target) { + left = mid; + } else { + right = mid; + } + } + + return Math.min(nums[left], nums[right]); + } + + /** + * @param num: + * a rotated sorted array + * @return: the minimum number in the array + */ + public int findMin2(int[] nums) { + if (nums == null || nums.length == 0) { + return -1; + } + + int left = 0, right = nums.length - 1; + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (nums[mid] == nums[right]) { + --right; + } else if (nums[mid] > nums[right]) { + left = mid; + } else { + right = mid; + } + } + + return Math.min(nums[left], nums[right]); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/FindPeak.java b/Algorithm-Java/src/Lintcode/Base/L2/FindPeak.java new file mode 100644 index 0000000..a52f51e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/FindPeak.java @@ -0,0 +1,29 @@ +package Lintcode.Base.L2; + +public class FindPeak { + /** + * @param A: + * An integers array. + * @return: return any of peek positions. + */ + public int findPeak(int[] A) { + int left = 0, right = A.length - 1, peak = -1; + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (A[mid] <= A[mid - 1]) { + right = mid; + } else if (A[mid] <= A[mid + 1]) { + left = mid; + } else { + peak = mid; + return peak; + } + } + return -1; + } + + public static void main(String[] args) { + int[] A = { 1, 2, 1, 3, 4, 5, 7, 6 }; + new FindPeak().findPeak(A); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/RecoverRotatedSortedArray.java b/Algorithm-Java/src/Lintcode/Base/L2/RecoverRotatedSortedArray.java new file mode 100644 index 0000000..2109fdf --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/RecoverRotatedSortedArray.java @@ -0,0 +1,34 @@ +package Lintcode.Base.L2; + +import java.util.ArrayList; + +public class RecoverRotatedSortedArray { + /** + * @param nums: + * The rotated sorted array + * @return: void + */ + public void recoverRotatedSortedArray(ArrayList nums) { + // find pivot + int pivot = 0; + for (int i = 1; i < nums.size(); i++) { + if (nums.get(i) < nums.get(i - 1)) { + pivot = i; + } + } + + reverse(nums, 0, pivot - 1); + reverse(nums, pivot, nums.size() - 1); + reverse(nums, 0, nums.size() - 1); + } + + void reverse(ArrayList nums, int left, int right) { + while (left < right) { + int temp = nums.get(left); + nums.set(left, nums.get(right)); + nums.set(right, temp); + ++left; + --right; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/RotateString.java b/Algorithm-Java/src/Lintcode/Base/L2/RotateString.java new file mode 100644 index 0000000..d516101 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/RotateString.java @@ -0,0 +1,30 @@ +package Lintcode.Base.L2; + +public class RotateString { + /** + * @param str: + * an array of char + * @param offset: + * an integer + * @return: nothing + */ + public void rotateString(char[] str, int offset) { + if (str == null || str.length == 0) { + return; + } + offset = offset % str.length; + reverse(str, 0, str.length - 1 - offset); + reverse(str, str.length - offset, str.length - 1); + reverse(str, 0, str.length - 1); + } + + void reverse(char[] str, int left, int right) { + while (left < right) { + char temp = str[left]; + str[left] = str[right]; + str[right] = temp; + ++left; + --right; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/Search.java b/Algorithm-Java/src/Lintcode/Base/L2/Search.java new file mode 100644 index 0000000..d1f6a30 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/Search.java @@ -0,0 +1,57 @@ +package Lintcode.Base.L2; + +import com.sun.accessibility.internal.resources.accessibility; + +public class Search { + /** + * @param A + * : an integer rotated sorted array + * @param target + * : an integer to be searched return : an integer + */ + public int search(int[] A, int target) { + if (A == null || A.length == 0) { + return -1; + } + int left = 0, right = A.length - 1; + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (A[mid] == target) { + return mid; + } else if (A[left] < A[mid]) { + if (target >= A[left] && target <= A[mid]) { + right = mid; + } else { + left = mid; + } + } else { + if (target >= A[mid] && target <= A[right]) { + left = mid; + } else { + right = mid; + } + } + } + + if (target == A[left]) { + return left; + } else if (target == A[right]) { + return right; + } else { + return -1; + } + } + + /** + * param A : an integer ratated sorted array and duplicates are allowed + * param target : an integer to be search return : a boolean + */ + public boolean search2(int[] A, int target) { + for (int i = 0; i < A.length; i++) { + if (A[i] == target) { + return true; + } + } + return false; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/SearchBigSortedArray.java b/Algorithm-Java/src/Lintcode/Base/L2/SearchBigSortedArray.java new file mode 100644 index 0000000..96d8f2a --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/SearchBigSortedArray.java @@ -0,0 +1,5 @@ +package Lintcode.Base.L2; + +public class SearchBigSortedArray { + +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/SearchInsert.java b/Algorithm-Java/src/Lintcode/Base/L2/SearchInsert.java new file mode 100644 index 0000000..9debedf --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/SearchInsert.java @@ -0,0 +1,33 @@ +package Lintcode.Base.L2; + +public class SearchInsert { + /** + * param A : an integer sorted array param target : an integer to be + * inserted return : an integer + */ + public int searchInsert(int[] A, int target) { + int left = 0, right = A.length - 1; + if (A == null || A.length == 0) { + return -1; + } + + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (A[mid] == target) { + right = mid; + } else if (A[mid] < target) { + left = mid; + } else { + right = mid; + } + } + + if (A[left] >= target && A[right] >= target) { + return left; + } else if (A[left] < target && A[right] < target) { + return right + 1; + } else { + return right; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L2/SearchRange.java b/Algorithm-Java/src/Lintcode/Base/L2/SearchRange.java new file mode 100644 index 0000000..8e52789 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L2/SearchRange.java @@ -0,0 +1,65 @@ +package Lintcode.Base.L2; + +public class SearchRange { + /** + * @param A + * : an integer sorted array + * @param target + * : an integer to be inserted return : a list of length 2, + * [index1, index2] + */ + public int[] searchRange(int[] A, int target) { + int[] result = new int[2]; + result[0] = -1; + result[1] = -1; + if (A == null || A.length == 0) { + return result; + } + + // lower bound + int left = 0, right = A.length - 1; + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (A[mid] == target) { + right = mid; + } else if (A[mid] > target) { + right = mid; + } else { + left = mid; + } + } + if (A[left] == target) { + result[0] = left; + }else if(A[right] == target){ + result[0] = right; + }else{ + result[0] = result[1] = -1; + return result; + } + + + // upper bound + left = 0; + right = A.length - 1; + while (left + 1 < right) { + int mid = left + (right - left) / 2; + if (A[mid] == target) { + left = mid; + } else if (A[mid] > target) { + right = mid; + } else { + left = mid; + } + } + if (A[right] == target) { + result[1] = right; + }else if(A[left] == target){ + result[1] = left; + }else{ + result[0] = result[1] = -1; + return result; + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/InsertNode.java b/Algorithm-Java/src/Lintcode/Base/L3/InsertNode.java new file mode 100644 index 0000000..a775a62 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/InsertNode.java @@ -0,0 +1,49 @@ +package Lintcode.Base.L3; + +import Lintcode.Base.L3.LevelOrder.TreeNode; + +public class InsertNode { + /** + * @param root: + * The root of the binary search tree. + * @param node: + * insert this node into the binary search tree + * @return: The root of the new binary search tree. + */ + public TreeNode insertNode(TreeNode root, TreeNode node) { + if (true) { + if (root == null) { + return node; + } + if (node.val >= root.val) { + root.right = insertNode(root.right, node); + } + if (node.val < root.val) { + root.left = insertNode(root.left, node); + } + return root; + } else { + TreeNode temp = root; + if (temp == null) { + return node; + } + while (temp != null) { + if (node.val >= temp.val) { + if (temp.right == null) { + temp.right = node; + } else { + temp = node.right; + } + } else if (node.val < temp.val) { + if (temp.left == null) { + temp.left = node; + } else { + temp = node.left; + } + } + } + + return root; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/IsBalanced.java b/Algorithm-Java/src/Lintcode/Base/L3/IsBalanced.java new file mode 100644 index 0000000..1f9a3fe --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/IsBalanced.java @@ -0,0 +1,37 @@ +package Lintcode.Base.L3; + +public class IsBalanced { + public class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param root: + * The root of binary tree. + * @return: True if this Binary tree is Balanced, or false. + */ + public boolean isBalanced(TreeNode root) { + return getDepth(root) != -1; + } + + int getDepth(TreeNode root) { + if (root == null) { + return 0; + } + + int left_depth = getDepth(root.left); + int right_depth = getDepth(root.right); + + if (left_depth == -1 || right_depth == -1 || Math.abs(left_depth - right_depth) > 1) { + return -1; + } + + return Math.max(left_depth, right_depth) + 1; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/IsValidBST.java b/Algorithm-Java/src/Lintcode/Base/L3/IsValidBST.java new file mode 100644 index 0000000..0d84f0c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/IsValidBST.java @@ -0,0 +1,26 @@ +package Lintcode.Base.L3; + +import Lintcode.Base.L3.LevelOrder.TreeNode; + +public class IsValidBST { + /** + * @param root: + * The root of binary tree. + * @return: True if the binary tree is BST, or false + */ + public boolean isValidBST(TreeNode root) { + return helper(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + boolean helper(TreeNode root, long min, long max) { + if (root == null) { + return true; + } else if (root.val <= min || root.val >= max) { + return false; + } + + boolean left_flag = helper(root.left, min, root.val); + boolean right_flag = helper(root.right, root.val, max); + return left_flag && right_flag; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/LevelOrder.java b/Algorithm-Java/src/Lintcode/Base/L3/LevelOrder.java new file mode 100644 index 0000000..475125c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/LevelOrder.java @@ -0,0 +1,85 @@ +package Lintcode.Base.L3; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.Queue; + +public class LevelOrder { + class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param root: + * The root of binary tree. + * @return: Level order a list of lists of integer + */ + public ArrayList> levelOrder(TreeNode root) { + ArrayList> results = new ArrayList<>(); + if (root == null) { + return results; + } + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + ArrayList result = new ArrayList<>(); + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + result.add(node.val); + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + results.add(result); + } + + return results; + } + + /** + * @param root: + * The root of binary tree. + * @return: buttom-up level order a list of lists of integer + */ + public ArrayList> levelOrderBottom(TreeNode root) { + ArrayList> results = new ArrayList<>(); + if (root == null) { + return results; + } + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + ArrayList result = new ArrayList<>(); + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + result.add(node.val); + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + results.add(result); + } + + Collections.reverse(results); + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/LowestCommonAncestor.java b/Algorithm-Java/src/Lintcode/Base/L3/LowestCommonAncestor.java new file mode 100644 index 0000000..e0cc3e4 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/LowestCommonAncestor.java @@ -0,0 +1,40 @@ +package Lintcode.Base.L3; + +public class LowestCommonAncestor { + public class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param root: + * The root of the binary search tree. + * @param A + * and B: two nodes in a Binary. + * @return: Return the least common ancestor(LCA) of the two nodes. + */ + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { + if (root == null || root == A || root == B) { + return root; + } + + TreeNode node_left = lowestCommonAncestor(root.left, A, B); + TreeNode node_right = lowestCommonAncestor(root.right, A, B); + + if (node_left != null && node_right != null) { + return root; + } else if (node_left != null) { + return node_left; + } else if (node_right != null) { + return node_right; + } else { + return null; + } + } + +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/MaxDepth.java b/Algorithm-Java/src/Lintcode/Base/L3/MaxDepth.java new file mode 100644 index 0000000..9b8b541 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/MaxDepth.java @@ -0,0 +1,29 @@ +package Lintcode.Base.L3; + +public class MaxDepth { + public class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param root: + * The root of binary tree. + * @return: An integer. + */ + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + + int left_depth = maxDepth(root.left); + int right_depth = maxDepth(root.right); + + return Math.max(left_depth, right_depth) + 1; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/MaxPathSum.java b/Algorithm-Java/src/Lintcode/Base/L3/MaxPathSum.java new file mode 100644 index 0000000..73cd069 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/MaxPathSum.java @@ -0,0 +1,34 @@ +package Lintcode.Base.L3; + +import Lintcode.Base.L3.LevelOrder.TreeNode; + +public class MaxPathSum { + /** + * @param root: + * The root of binary tree. + * @return: An integer. + */ + public int maxPathSum(TreeNode root) { + return maxPathSumHeler(root).double_sum; + } + + class ReturnWrapper { + public int single_sum = 0, double_sum = Integer.MIN_VALUE; + } + + ReturnWrapper maxPathSumHeler(TreeNode root) { + if (root == null) { + return new ReturnWrapper(); + } + + ReturnWrapper left_wrapper = maxPathSumHeler(root.left); + ReturnWrapper right_wrapper = maxPathSumHeler(root.right); + + ReturnWrapper wrapper = new ReturnWrapper(); + wrapper.single_sum = Math.max(0, Math.max(left_wrapper.single_sum, right_wrapper.single_sum) + root.val); + wrapper.double_sum = Math.max(left_wrapper.single_sum + right_wrapper.single_sum + root.val, + Math.max(left_wrapper.double_sum, right_wrapper.double_sum)); + + return wrapper; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/PreorderTraversal.java b/Algorithm-Java/src/Lintcode/Base/L3/PreorderTraversal.java new file mode 100644 index 0000000..1067ace --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/PreorderTraversal.java @@ -0,0 +1,37 @@ +package Lintcode.Base.L3; + +import java.util.ArrayList; + +public class PreorderTraversal { + public class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param root: + * The root of binary tree. + * @return: Preorder in ArrayList which contains node values. + */ + public ArrayList preorderTraversal(TreeNode root) { + if (root == null) { + return new ArrayList<>(); + } + + ArrayList result = new ArrayList<>(); + + ArrayList left_list = preorderTraversal(root.left); + ArrayList right_list = preorderTraversal(root.right); + + result.add(root.val); + result.addAll(left_list); + result.addAll(right_list); + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/SearchRange.java b/Algorithm-Java/src/Lintcode/Base/L3/SearchRange.java new file mode 100644 index 0000000..41e7595 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/SearchRange.java @@ -0,0 +1,37 @@ +package Lintcode.Base.L3; + +import java.util.ArrayList; + +import Lintcode.Base.L3.LevelOrder.TreeNode; + +public class SearchRange { + /** + * @param root: + * The root of the binary search tree. + * @param k1 + * and k2: range k1 to k2. + * @return: Return all keys that k1<=key<=k2 in ascending order. + */ + public ArrayList searchRange(TreeNode root, int k1, int k2) { + ArrayList result = new ArrayList<>(); + if (root == null) { + return result; + } + + if (root.val >= k1) { + ArrayList left_result = searchRange(root.left, k1, k2); + result.addAll(left_result); + } + + if (root.val >= k1 && root.val <= k2) { + result.add(root.val); + } + + if (root.val <= k2) { + ArrayList right_result = searchRange(root.right, k1, k2); + result.addAll(right_result); + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L3/ZigzagLevelOrder.java b/Algorithm-Java/src/Lintcode/Base/L3/ZigzagLevelOrder.java new file mode 100644 index 0000000..f52eaff --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L3/ZigzagLevelOrder.java @@ -0,0 +1,48 @@ +package Lintcode.Base.L3; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.Queue; + +import Lintcode.Base.L3.LevelOrder.TreeNode; + +public class ZigzagLevelOrder { + /** + * @param root: + * The root of binary tree. + * @return: A list of lists of integer include the zigzag level order + * traversal of its nodes' values + */ + public ArrayList> zigzagLevelOrder(TreeNode root) { + ArrayList> results = new ArrayList<>(); + if (root == null) { + return results; + } + + Queue queue = new LinkedList<>(); + queue.add(root); + int order = 0; + + while (!queue.isEmpty()) { + ArrayList result = new ArrayList<>(); + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + result.add(node.val); + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + if (order++ % 2 == 1) { + Collections.reverse(result); + } + results.add(result); + } + + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/CopyRandomList.java b/Algorithm-Java/src/Lintcode/Base/L6/CopyRandomList.java new file mode 100644 index 0000000..c623981 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/CopyRandomList.java @@ -0,0 +1,49 @@ +package Lintcode.Base.L6; + +import java.util.HashMap; + +public class CopyRandomList { + /** + * @param head: + * The head of linked list with a random pointer. + * @return: A new head of a deep copy of the list. + */ + class RandomListNode { + int label; + RandomListNode next, random; + + RandomListNode(int x) { + this.label = x; + } + } + + public RandomListNode copyRandomList(RandomListNode head) { + HashMap mapper = new HashMap<>(); + RandomListNode pre_head = new RandomListNode(0), temp_new = pre_head; + RandomListNode temp = head, new_node; + + while (temp != null) { + if (mapper.containsKey(temp)) { + new_node = mapper.get(temp); + } else { + new_node = new RandomListNode(temp.label); + mapper.put(temp, new_node); + } + temp_new.next = new_node; + + if (temp.random != null) { + if (mapper.containsKey(temp.random)) { + new_node.random = mapper.get(temp.random); + } else { + new_node.random = new RandomListNode(temp.random.label); + mapper.put(temp.random, new_node.random); + } + } + + temp_new = new_node; + temp = temp.next; + } + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/DeleteDuplicates.java b/Algorithm-Java/src/Lintcode/Base/L6/DeleteDuplicates.java new file mode 100644 index 0000000..a07946a --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/DeleteDuplicates.java @@ -0,0 +1,57 @@ +package Lintcode.Base.L6; + +public class DeleteDuplicates { + static class ListNode { + int val; + ListNode next; + + public ListNode(int x) { + val = x; + next = null; + } + } + + /** + * @param ListNode + * head is the head of the linked list + * @return: ListNode head of linked list + */ + public static ListNode deleteDuplicates(ListNode head) { + ListNode temp = head; + + while (temp != null) { + while (temp.next != null && temp.val == temp.next.val) { + temp.next = temp.next.next; + } + temp = temp.next; + } + + return head; + } + + /** + * @param ListNode + * head is the head of the linked list + * @return: ListNode head of the linked list + */ + public static ListNode deleteDuplicates2(ListNode head) { + ListNode pre_head = new ListNode(-1); + pre_head.next = head; + + ListNode temp = pre_head; + while (temp.next != null && temp.next.next != null) { + if (temp.next.val == temp.next.next.val) { + int check_Val = temp.next.val; + ListNode loop = temp.next.next; + while (loop != null && loop.val == check_Val) { + loop = loop.next; + } + temp.next = loop; + } else { + temp = temp.next; + } + } + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/MergeKLists.java b/Algorithm-Java/src/Lintcode/Base/L6/MergeKLists.java new file mode 100644 index 0000000..1438d4b --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/MergeKLists.java @@ -0,0 +1,56 @@ +package Lintcode.Base.L6; + +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +import Lintcode.Base.L6.DeleteDuplicates.ListNode; + +public class MergeKLists { + class PriorityComp implements Comparator { + + @Override + public int compare(ListNode left, ListNode right) { + if (left == null) { + return 1; + } else if (right == null) { + return -1; + } + return left.val - right.val; + } + + } + + /** + * @param lists: + * a list of ListNode + * @return: The head of one sorted list. + */ + public ListNode mergeKLists(List lists) { + if (lists == null || lists.size() == 0) { + return null; + } + + ListNode pre_head = new ListNode(0), temp = pre_head; + PriorityQueue queue = new PriorityQueue<>(lists.size(), new PriorityComp()); + for (int i = 0; i < lists.size(); i++) { + if (lists.get(i) != null) { + queue.add(lists.get(i)); + } + } + + while (!queue.isEmpty()) { + ListNode node = queue.poll(); + + temp.next = node; + temp = node; + + if (node.next != null) { + queue.add(node.next); + node = node.next; + } + } + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/Partition.java b/Algorithm-Java/src/Lintcode/Base/L6/Partition.java new file mode 100644 index 0000000..b1a7f0d --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/Partition.java @@ -0,0 +1,37 @@ +package Lintcode.Base.L6; + +import Lintcode.Base.L6.DeleteDuplicates.ListNode; + +public class Partition { + /** + * @param head: + * The first node of linked list. + * @param x: + * an integer + * @return: a ListNode + */ + public ListNode partition(ListNode head, int x) { + if (head == null) { + return null; + } + + ListNode pre_head_small = new ListNode(0); + ListNode pre_head_large = new ListNode(0); + ListNode temp_small = pre_head_small, temp_large = pre_head_large; + + while (head != null) { + if (head.val < x) { + temp_small.next = head; + temp_small = head; + } else { + temp_large.next = head; + temp_large = head; + } + head = head.next; + } + + temp_large.next = null; + temp_small.next = pre_head_large.next; + return pre_head_small.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/ReorderList.java b/Algorithm-Java/src/Lintcode/Base/L6/ReorderList.java new file mode 100644 index 0000000..c404cb9 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/ReorderList.java @@ -0,0 +1,14 @@ +package Lintcode.Base.L6; + +import Lintcode.Base.L6.DeleteDuplicates.ListNode; + +public class ReorderList { + /** + * @param head: + * The head of linked list. + * @return: void + */ + public void reorderList(ListNode head) { + return; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/Reverse.java b/Algorithm-Java/src/Lintcode/Base/L6/Reverse.java new file mode 100644 index 0000000..cb883ac --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/Reverse.java @@ -0,0 +1,56 @@ +package Lintcode.Base.L6; + +import Lintcode.Base.L6.DeleteDuplicates.ListNode; + +public class Reverse { + /** + * @param head: + * The head of linked list. + * @return: The new head of reversed linked list. + */ + public ListNode reverse(ListNode head) { + ListNode pre_node = null; + while (head != null) { + ListNode next_node = head.next; + head.next = pre_node; + + pre_node = head; + head = next_node; + } + return pre_node; + } + + /** + * @param ListNode + * head is the head of the linked list + * @oaram m and n + * @return: The head of the reversed ListNode + */ + public ListNode reverseBetween(ListNode head, int m, int n) { + ListNode pre_head = new ListNode(0); + pre_head.next = head; + + // 1->2->3->4->5->null + // 1->4->3->2->5->null + + ListNode temp = pre_head; + for (int i = 0; i < m - 1; i++) { + temp = temp.next; + } + + ListNode pre_last_node = temp, cur_last_node = temp.next; + ListNode pre_node = pre_last_node.next, cur_node = cur_last_node.next; + for (int i = m; i < n; i++) { + ListNode next_node = cur_node.next; + cur_node.next = pre_node; + + pre_node = cur_node; + cur_node = next_node; + } + + pre_last_node.next = pre_node; + cur_last_node.next = cur_node; + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/ReverseKGroup.java b/Algorithm-Java/src/Lintcode/Base/L6/ReverseKGroup.java new file mode 100644 index 0000000..976b554 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/ReverseKGroup.java @@ -0,0 +1,65 @@ +package Lintcode.Base.L6; + +import Lintcode.Base.L6.DeleteDuplicates.ListNode; + +public class ReverseKGroup { + /** + * @param head + * a ListNode + * @param k + * an integer + * @return a ListNode + */ + public ListNode reverseKGroup(ListNode head, int k) { + if (head == null) { + return null; + } + + ListNode pre_head = new ListNode(0); + pre_head.next = head; + + ListNode temp = pre_head; + while (temp != null) { + temp = reverseByK(temp, k); + } + + return pre_head.next; + } + + ListNode reverseByK(ListNode head, int k) { + // check space + ListNode temp = head; + for (int i = 0; i < k; i++) { + if (temp.next == null) { + return null; + } + temp = temp.next; + } + + // reverse + ListNode pre_last_node = head, cur_last_node = head.next; + ListNode pre_node = head.next, cur_node = pre_node.next; + for (int i = 0; i < k - 1; i++) { + ListNode next_node = cur_node.next; + cur_node.next = pre_node; + + pre_node = cur_node; + cur_node = next_node; + } + + pre_last_node.next = pre_node; + cur_last_node.next = cur_node; + + return cur_last_node; + } + + public static void main(String[] args) { + ListNode n1 = new ListNode(1), n2 = new ListNode(2), n3 = new ListNode(3), n4 = new ListNode(4), + n5 = new ListNode(5); + n1.next = n2; + n2.next = n3; + n3.next = n4; + n4.next = n5; + new ReverseKGroup().reverseKGroup(n1, 2); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/SortList.java b/Algorithm-Java/src/Lintcode/Base/L6/SortList.java new file mode 100644 index 0000000..f70aba1 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/SortList.java @@ -0,0 +1,59 @@ +package Lintcode.Base.L6; + +import Lintcode.Base.L6.DeleteDuplicates.ListNode; + +public class SortList { + /** + * @param head: + * The head of linked list. + * @return: You should return the head of the sorted linked list, using + * constant space complexity. + */ + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode mid = findMiddle(head); + ListNode right = sortList(mid.next); + mid.next = null; + ListNode left = sortList(head); + return merge(left, right); + } + + ListNode merge(ListNode head1, ListNode head2) { + ListNode pre_head = new ListNode(0); + ListNode temp = pre_head; + + while (head1 != null && head2 != null) { + if (head1.val <= head2.val) { + temp.next = head1; + head1 = head1.next; + } else { + temp.next = head2; + head2 = head2.next; + } + temp = temp.next; + } + while (head1 != null) { + temp.next = head1; + head1 = head1.next; + } + while (head2 != null) { + temp.next = head2; + head2 = head2.next; + } + + return pre_head.next; + } + + ListNode findMiddle(ListNode head) { + ListNode slow_node = head, fast_node = head.next; + + while (fast_node != null && fast_node.next != null) { + slow_node = slow_node.next; + fast_node = fast_node.next.next; + } + + return slow_node; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L6/SortedListToBST.java b/Algorithm-Java/src/Lintcode/Base/L6/SortedListToBST.java new file mode 100644 index 0000000..e8d8094 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L6/SortedListToBST.java @@ -0,0 +1,65 @@ +package Lintcode.Base.L6; + +public class SortedListToBST { + class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } + } + + class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param head: + * The first node of linked list. + * @return: a tree node + */ + public TreeNode sortedListToBST(ListNode head) { + int size; + + current_node = head; + size = getListLength(head); + + return sortedListToBSTHelper(size); + } + + static ListNode current_node; + + TreeNode sortedListToBSTHelper(int size) { + if (size <= 0) { + return null; + } + + TreeNode left_node = sortedListToBSTHelper(size / 2); + TreeNode node = new TreeNode(current_node.val); + current_node = current_node.next; + TreeNode right_node = sortedListToBSTHelper(size - 1 - size / 2); + + node.left = left_node; + node.right = right_node; + return node; + } + + int getListLength(ListNode head) { + int size = 0; + + while (head != null) { + size++; + head = head.next; + } + + return size; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/FindMedianSortedArrays.java b/Algorithm-Java/src/Lintcode/Base/L7/FindMedianSortedArrays.java new file mode 100644 index 0000000..30ea12e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/FindMedianSortedArrays.java @@ -0,0 +1,39 @@ +package Lintcode.Base.L7; + +public class FindMedianSortedArrays { + /** + * @param A: + * An integer array. + * @param B: + * An integer array. + * @return: a double whose format is *.5 or *.0 + */ + public double findMedianSortedArrays(int[] A, int[] B) { + int len = A.length + B.length; + if (len % 2 == 1) { + return findKth(A, 0, B, 0, len / 2 + 1); + } + return ( + findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1) + ) / 2.0; + } + + int findKth(int[] A, int A_start, int[] B, int B_start, int k) { + if (A_start >= A.length) { + return B[B_start + k - 1]; + } + if (B_start >= B.length) { + return A[A_start + k - 1]; + } + if (k == 1) { + return Math.min(A[A_start], B[B_start]); + } + int A_key = A_start + k / 2 - 1 < A.length ? A[A_start + k / 2 - 1] : Integer.MAX_VALUE; + int B_key = B_start + k / 2 - 1 < B.length ? B[B_start + k / 2 - 1] : Integer.MAX_VALUE; + if (A_key < B_key) { + return findKth(A, A_start + k / 2, B, B_start, k - k / 2); + } else { + return findKth(A, A_start, B, B_start + k / 2, k - k / 2); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/MergeSortedArray.java b/Algorithm-Java/src/Lintcode/Base/L7/MergeSortedArray.java new file mode 100644 index 0000000..1f45d82 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/MergeSortedArray.java @@ -0,0 +1,53 @@ +package Lintcode.Base.L7; + + +public class MergeSortedArray { + /** + * @param A: + * sorted integer array A which has m elements, but size of A is + * m+n + * @param B: + * sorted integer array B which has n elements + * @return: void + */ + public void mergeSortedArray(int[] A, int m, int[] B, int n) { + int i = m, j = n, k = A.length - 1; + while (i >= 0 && j >= 0) { + if (A[i] >= B[j]) { + A[k--] = A[i--]; + } else { + A[k--] = B[j--]; + } + } + + while (j >= 0) { + A[k--] = B[j--]; + } + } + + /** + * @param A and B: sorted integer array A and B. + * @return: A new sorted integer array + */ + public int[] mergeSortedArray(int[] A, int[] B) { + int[] result = new int[A.length + B.length]; + + int i = 0, j = 0, k = 0; + while (i < A.length && j < B.length) { + if (A[i] <= B[j]) { + result[k++] = A[i++]; + }else{ + result[k++] = B[j++]; + } + } + + while (i < A.length) { + result[k++] = A[i++]; + } + while (j < B.length) { + result[k++] = B[j++]; + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/MinSubArray.java b/Algorithm-Java/src/Lintcode/Base/L7/MinSubArray.java new file mode 100644 index 0000000..affe87b --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/MinSubArray.java @@ -0,0 +1,22 @@ +package Lintcode.Base.L7; + +import java.util.ArrayList; + +public class MinSubArray { + /** + * @param nums: + * a list of integers + * @return: A integer indicate the sum of minimum subarray + */ + public int minSubArray(ArrayList nums) { + if (nums == null || nums.size() == 0) { + return 0; + } + int current_min = nums.get(0), min = nums.get(0); + for (int i = 1; i < nums.size(); i++) { + current_min = Math.min(nums.get(i), current_min + nums.get(i)); + min = Math.min(min, current_min); + } + return min; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/PartitionArray.java b/Algorithm-Java/src/Lintcode/Base/L7/PartitionArray.java new file mode 100644 index 0000000..b49a7e6 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/PartitionArray.java @@ -0,0 +1,38 @@ +package Lintcode.Base.L7; + +public class PartitionArray { + /** + * @param nums: + * The integer array you should partition + * @param k: + * As description return: The index after partition + */ + public int partitionArray(int[] nums, int k) { + if (nums == null || nums.length == 0) { + return 0; + } + int left = 0, right = nums.length; + + while (left < right) { + while (left <= right && nums[right] >= k) { + --right; + } + + while (left <= right && nums[left] <= k) { + ++left; + } + + if (left <= right) { + int temp = nums[left]; + nums[left] = nums[right]; + nums[right] = temp; + + --right; + ++left; + } + + } + + return left; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/Rerange.java b/Algorithm-Java/src/Lintcode/Base/L7/Rerange.java new file mode 100644 index 0000000..bf28f4d --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/Rerange.java @@ -0,0 +1,12 @@ +package Lintcode.Base.L7; + +public class Rerange { + /** + * @param A: + * An integer array. + * @return: void + */ + public void rerange(int[] A) { + // write your code here + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/SortColors.java b/Algorithm-Java/src/Lintcode/Base/L7/SortColors.java new file mode 100644 index 0000000..b9164af --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/SortColors.java @@ -0,0 +1,30 @@ +package Lintcode.Base.L7; + +public class SortColors { + /** + * @param nums: + * A list of integer which is 0, 1 or 2 + * @return: nothing + */ + public void sortColors(int[] nums) { + if (nums == null || nums.length == 0) { + return; + } + int left = 0, right = nums.length - 1, idx = 0; + while (idx <= right) { + if (nums[idx] == 2) { + swap(nums, idx, right--); + }else if(nums[idx] == 0){ + swap(nums, idx++, left++); + }else if(nums[idx] == 1){ + ++idx; + } + } + } + + void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/SortLetters.java b/Algorithm-Java/src/Lintcode/Base/L7/SortLetters.java new file mode 100644 index 0000000..275c984 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/SortLetters.java @@ -0,0 +1,30 @@ +package Lintcode.Base.L7; + +public class SortLetters { + /** + *@param chars: The letter array you should sort by Case + *@return: void + */ + public void sortLetters(char[] chars) { + int left = 0 , right = chars.length - 1; + while (left < right) { + while (left < right && isLowerCase(chars[left])) { + ++left; + } + + while (left < right && !isLowerCase(chars[right])) { + --right; + } + + if (left < right) { + char temp = chars[left]; + chars[left] = chars[right]; + chars[right] = temp; + } + } + } + + boolean isLowerCase(char ch){ + return ch >= 'a' && ch <= 'z'; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L7/SubarraySum.java b/Algorithm-Java/src/Lintcode/Base/L7/SubarraySum.java new file mode 100644 index 0000000..776499e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L7/SubarraySum.java @@ -0,0 +1,39 @@ +package Lintcode.Base.L7; + +import java.util.ArrayList; +import java.util.HashMap; + +public class SubarraySum { + /** + * @param nums: + * A list of integers + * @return: A list of integers includes the index of the first number and + * the index of the last number + */ + public ArrayList subarraySum(int[] nums) { + int len = nums.length; + + ArrayList ans = new ArrayList(); + HashMap map = new HashMap(); + + int sum = 0; + for (int i = 0; i < len; i++) { + sum += nums[i]; + + if (map.containsKey(sum)) { + ans.add(map.get(sum) + 1); + ans.add(i); + return ans; + } + + map.put(sum, i); + } + + return ans; + } + + public static void main(String[] args) { + int[] nums = { 1, -3, 1, 2, -3, 4 }; + new SubarraySum().subarraySum(nums); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L8/LargestRectangleArea.java b/Algorithm-Java/src/Lintcode/Base/L8/LargestRectangleArea.java new file mode 100644 index 0000000..11075aa --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L8/LargestRectangleArea.java @@ -0,0 +1,35 @@ +package Lintcode.Base.L8; + +import java.util.Stack; + +public class LargestRectangleArea { + /** + * @param height: + * A list of integer + * @return: The area of largest rectangle in the histogram + */ + public int largestRectangleArea(int[] height) { + if (height == null || height.length == 0) { + return 0; + } + + Stack stack = new Stack(); + int max = 0; + for (int i = 0; i <= height.length; i++) { + int curt = (i == height.length) ? -1 : height[i]; + while (!stack.isEmpty() && curt <= height[stack.peek()]) { + int h = height[stack.pop()]; + int w = stack.isEmpty() ? i : i - stack.peek() - 1; + max = Math.max(max, h * w); + } + stack.push(i); + } + + return max; + } + + public static void main(String[] args) { + int[] height = {2,1,5,6,2,3}; + new LargestRectangleArea().largestRectangleArea(height); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L8/LongestConsecutive.java b/Algorithm-Java/src/Lintcode/Base/L8/LongestConsecutive.java new file mode 100644 index 0000000..a4b6cd9 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L8/LongestConsecutive.java @@ -0,0 +1,41 @@ +package Lintcode.Base.L8; + +import java.util.HashSet; + +public class LongestConsecutive { + /** + * @param nums: + * A list of integers + * @return an integer + */ + public int longestConsecutive(int[] nums) { + HashSet set = new HashSet<>(); + for (int i = 0; i < nums.length; i++) { + set.add(nums[i]); + } + + int longest = 0; + for (int i = 0; i < nums.length; i++) { + int down = nums[i] - 1; + while (set.contains(down)) { + set.remove(down); + down--; + } + + int up = nums[i] + 1; + while (set.contains(up)) { + set.remove(up); + up++; + } + + longest = Math.max(longest, up - down - 1); + } + + return longest; + } + + public static void main(String[] args) { + int[] nums = {100, 4, 200, 1, 3, 2}; + new LongestConsecutive().longestConsecutive(nums); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L8/MaxTree.java b/Algorithm-Java/src/Lintcode/Base/L8/MaxTree.java new file mode 100644 index 0000000..acdc531 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L8/MaxTree.java @@ -0,0 +1,48 @@ +package Lintcode.Base.L8; + +import java.util.LinkedList; + +public class MaxTree { + class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } + } + + /** + * @param A: + * Given an integer array with no duplicates. + * @return: The root of max tree. + */ + public TreeNode maxTree(int[] A) { + // write your code here + if (A == null || A.length == 0) { + return null; + } + LinkedList stack = new LinkedList(); + for (int i = 0; i < A.length; i++) { + TreeNode cur = new TreeNode(A[i]); + while (!stack.isEmpty() && cur.val > stack.peek().val) { + cur.left = stack.pop(); + } + if (!stack.isEmpty()) { + stack.peek().right = cur; + } + stack.push(cur); + } + TreeNode result = new TreeNode(0); + while (!stack.isEmpty()) { + result = stack.pop(); + } + return result; + } + + public static void main(String[] args) { + int[] A = { 2, 5, 6, 0, 3, 1 }; + new MaxTree().maxTree(A); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L8/MinStack.java b/Algorithm-Java/src/Lintcode/Base/L8/MinStack.java new file mode 100644 index 0000000..0307cf5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L8/MinStack.java @@ -0,0 +1,32 @@ +package Lintcode.Base.L8; + +import java.util.Stack; + +public class MinStack { + + Stack num_stack = null, min_stack = null; + + public MinStack() { + num_stack = new Stack<>(); + min_stack = new Stack<>(); + } + + public void push(int number) { + num_stack.push(number); + if (min_stack.isEmpty() || min_stack.peek() > number) { + min_stack.push(number); + } else { + min_stack.push(min_stack.peek()); + } + } + + public int pop() { + int num = num_stack.pop(); + min_stack.pop(); + return num; + } + + public int min() { + return min_stack.peek(); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L8/Queue.java b/Algorithm-Java/src/Lintcode/Base/L8/Queue.java new file mode 100644 index 0000000..dac298f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L8/Queue.java @@ -0,0 +1,36 @@ +package Lintcode.Base.L8; + +import java.util.Stack; + +public class Queue { + private Stack stack1; + private Stack stack2; + + public Queue() { + stack1 = new Stack<>(); + stack2 = new Stack<>(); + } + + public void push(int element) { + stack1.push(element); + } + + public int pop() { + if (stack2.isEmpty()) { + while (!stack1.isEmpty()) { + stack2.push(stack1.pop()); + } + } + + return stack2.pop(); + } + + public int top() { + if (stack2.isEmpty()) { + while (!stack1.isEmpty()) { + stack2.push(stack1.pop()); + } + } + return stack2.peek(); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/L8/Rehashing.java b/Algorithm-Java/src/Lintcode/Base/L8/Rehashing.java new file mode 100644 index 0000000..d268a9a --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/L8/Rehashing.java @@ -0,0 +1,22 @@ +package Lintcode.Base.L8; + +public class Rehashing { + class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } + } + + /** + * @param hashTable: + * A list of The first node of linked list + * @return: A list of The first node of linked list which have twice size + */ + public ListNode[] rehashing(ListNode[] hashTable) { + return null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/BinarySearch.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/BinarySearch.java new file mode 100644 index 0000000..bf8beba --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/BinarySearch.java @@ -0,0 +1,32 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class BinarySearch { + /** + * @param nums: The integer array. + * @param target: Target to find. + * @return: The first position of target. Position starts from 0. + */ + public int binarySearch(int[] nums, int target) { + if (nums == null || nums.length == 0) { + return -1; + } + + int start = 0, end = nums.length - 1; + while(start + 1 < end){ + int mid = start + (end - start) / 2; + if (nums[mid] >= target){ + end = mid; + }else{ + start = mid; + } + } + + if(nums[start] == target){ + return start; + }else if(nums[end] == target){ + return end; + }else{ + return -1; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/FindMin.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/FindMin.java new file mode 100644 index 0000000..7a9adf8 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/FindMin.java @@ -0,0 +1,38 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class FindMin { + public int findMin(int[] nums) { + if (nums == null || nums.length == 0) { + return -1; + } + + int start = 0, end = nums.length - 1; + while (start + 1 < end) { + int mid = start + (end - start) / 2; + if (nums[mid] >= nums[start] && nums[mid] >= nums[end]) { + start = mid; + } else if (nums[mid] <= nums[start] && nums[mid] <= nums[end]) { + end = mid; + } else if (nums[mid] >= nums[start] && nums[mid] <= nums[end]) { + end = mid; + } else if (nums[mid] <= nums[start] && nums[mid] >= nums[end]) { + start = mid; + } + } + + return Math.min(nums[start], nums[end]); + } + + /** + * @param num: a rotated sorted array + * @return: the minimum number in the array + * @throws Exception + */ + public int findMin2(int[] nums) throws Exception { + if (nums == null || nums.length == 0) { + return -1; + } + + throw new Exception("no solution"); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/FindPeak.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/FindPeak.java new file mode 100644 index 0000000..a28d3b4 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/FindPeak.java @@ -0,0 +1,27 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class FindPeak { + /** + * @param A: + * An integers array. + * @return: return any of peek positions. + */ + public int findPeak(int[] A) { + int start = 1, end = A.length - 2; + while (start + 1 < end) { + int mid = start + (end - start) / 2; + if (A[mid] < A[mid + 1]) { + start = mid; + } else if (A[mid] > A[mid + 1]) { + end = mid; + } + } + + // check start + if(A[start] < A[end]){ + return end; + }else{ + return start; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/Search.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/Search.java new file mode 100644 index 0000000..6377d5e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/Search.java @@ -0,0 +1,44 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class Search { + /** + * @param A + * : an integer rotated sorted array + * @param target + * : an integer to be searched return : an integer + */ + public int search(int[] A, int target) { + if (A == null || A.length == 0) { + return -1; + } + + int start = 0, end = A.length - 1; + while (start + 1 < end) { + int mid = start + (end - start) / 2; + if (A[mid] == target) { + return mid; + } + // diff side + if (target >= A[start] && A[mid] <= A[start]) { + end = mid; + } else if (target < A[start] && A[mid] > A[start]) { + start = mid; + } else { + if (A[mid] > target) { + end = mid; + } else { + start = mid; + } + } + + } + + if (A[start] == target) { + return start; + } else if (A[end] == target) { + return end; + } else { + return -1; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchInsert.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchInsert.java new file mode 100644 index 0000000..6df7694 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchInsert.java @@ -0,0 +1,32 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class SearchInsert { + /** + * param A : an integer sorted array + * param target : an integer to be inserted + * return : an integer + */ + public int searchInsert(int[] A, int target) { + if (A == null || A.length == 0){ + return 0; + } + + int start = 0, end = A.length - 1; + while(start + 1 < end){ + int mid = start + (end - start) / 2; + if(A[mid] <= target){ + start = mid; + }else{ + end = mid; + } + } + + if (target <= A[start]){ + return start; + }else if (target >= A[start] && target <= A[end]){ + return 1 + start; + }else{ + return 1 + end; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchMatrix.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchMatrix.java new file mode 100644 index 0000000..00c169a --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchMatrix.java @@ -0,0 +1,69 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class SearchMatrix { + /** + * @param matrix, + * a list of lists of integers + * @param target, + * an integer + * @return a boolean, indicate whether matrix contains target + */ + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return false; + } + + int start = 0, end = matrix.length * matrix[0].length - 1; + while (start + 1 < end) { + int mid = start + (end - start) / 2; + int val = matrix[mid / matrix[0].length][mid % matrix[0].length]; + if (target == val) { + return true; + } else if (target < val) { + end = mid; + } else { + start = mid; + } + } + + if (matrix[start / matrix[0].length][start % matrix[0].length] == target + || matrix[end / matrix[0].length][end % matrix[0].length] == target) { + return true; + } else { + return false; + } + } + + /** + * @param matrix: + * A list of lists of integers + * @param: A + * number you want to search in the matrix + * @return: An integer indicate the occurrence of target in the given matrix + */ + public int searchMatrix2(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return 0; + } + + int row = matrix.length - 1, col = 0; + int cnt = 0; + + while (row >= 0 && col < matrix[0].length) { + if (matrix[row][col] == target) { + ++cnt; + if (row >= 0) { + --row; + } else if (col < matrix[0].length) { + ++col; + } + } else if (matrix[row][col] < target) { + ++col; + } else { + --row; + } + } + + return cnt; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchRange.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchRange.java new file mode 100644 index 0000000..fbb3ac6 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/SearchRange.java @@ -0,0 +1,54 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class SearchRange { + /** + * @param A + * : an integer sorted array + * @param target + * : an integer to be inserted return : a list of length 2, + * [index1, index2] + */ + public int[] searchRange(int[] A, int target) { + int[] result = new int[2]; + result[0] = -1; + result[1] = -1; + if (A == null || A.length == 0) { + return result; + } + + // find start + int start = 0, end = A.length - 1; + while (start + 1 < end) { + int mid = start + (end - start) / 2; + if (A[mid] >= target) { + end = mid; + } else { + start = mid; + } + } + if (A[start] == target) { + result[0] = start; + } else if (A[end] == target) { + result[0] = end; + } + + // find last + start = 0; + end = A.length - 1; + while (start + 1 < end) { + int mid = start + (end - start) / 2; + if (A[mid] > target) { + end = mid; + } else { + start = mid; + } + } + if (A[end] == target) { + result[1] = end; + } else if (A[start] == target) { + result[1] = start; + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/Sqrt.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/Sqrt.java new file mode 100644 index 0000000..235ce34 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/Sqrt.java @@ -0,0 +1,25 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class Sqrt { + /** + * @param x: An integer + * @return: The sqrt of x + */ + public int sqrt(int x) { + long start = 0, end = x; + while(start + 1 < end){ + long mid = start + (end - start) / 2; + if(mid*mid <= x){ + start = mid; + }else if(mid*mid > x){ + end = mid; + } + } + + if (end * end == x){ + return (int) end; + }else { + return (int) start; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/WoodCut.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/WoodCut.java new file mode 100644 index 0000000..987196f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinarySearchLadder/WoodCut.java @@ -0,0 +1,42 @@ +package Lintcode.Base.Ladders.BinarySearchLadder; + +public class WoodCut { + /** + *@param L: Given n pieces of wood with length L[i] + *@param k: An integer + *return: The maximum length of the small pieces. + */ + public int woodCut(int[] L, int k) { + int end = 0; + for(int l : L){ + end = Math.max(end, l); + } + + int start = 1; + while (start + 1 < end){ + int mid = start + (end - start) / 2; + int cnt = count(L, mid); + if (cnt >= k){ + start = mid; + }else{ + end = mid; + } + } + + if(count(L, end) >= k){ + return end; + }else if(count(L, start) >= k){ + return start; + }else{ + return 0; + } + } + + int count(int[] L, long length){ + int cnt = 0; + for(int l : L){ + cnt += l / length; + } + return cnt; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/BuildTree.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/BuildTree.java new file mode 100644 index 0000000..30a52c1 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/BuildTree.java @@ -0,0 +1,70 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class BuildTree { + /** + * @param preorder + * : A list of integers that preorder traversal of a tree + * @param inorder + * : A list of integers that inorder traversal of a tree + * @return : Root of a tree + */ + public TreeNode buildTree(int[] preorder, int[] inorder) { + return buildTree(preorder, inorder, 0, preorder.length, 0, inorder.length); + } + + public TreeNode buildTree(int[] preorder, int[] inorder, int ps, int pe, int is, int ie) { + if (ps > pe || is > ie || ps >= preorder.length || ps < 0) { + return null; + } + TreeNode root = new TreeNode(preorder[ps]); + int pivot_idx_in_inorder = findSplit(preorder, inorder, ps, pe, is, ie); + int left_interval = pivot_idx_in_inorder - 1 - is; + // int right_interval = ie - pivot_idx_in_inorder - 1; + root.left = buildTree(preorder, inorder, ps + 1, ps + 1 + left_interval, is, pivot_idx_in_inorder - 1); + root.right = buildTree(preorder, inorder, ps + 1 + left_interval + 1, pe, pivot_idx_in_inorder + 1, ie); + return root; + } + + int findSplit(int[] preorder, int[] inorder, int ps, int pe, int is, int ie) { + int pivot = preorder[ps]; + for (int i = is; i <= ie; ++i) { + if (inorder[i] == pivot) { + return i; + } + } + return -1; + } + + /** + * @param inorder + * : A list of integers that inorder traversal of a tree + * @param postorder + * : A list of integers that postorder traversal of a tree + * @return : Root of a tree + */ + public TreeNode buildTree2(int[] inorder, int[] postorder) { + return buildTree2(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1); + } + + public TreeNode buildTree2(int[] inorder, int[] postorder, int is, int ie, int ps, int pe) { + if (ps > pe || is > ie || pe < 0 || pe >= postorder.length) { + return null; + } + TreeNode root = new TreeNode(postorder[pe]); + int pivot_idx_in_inorder = findSplit2(inorder, postorder, is, ie, ps, pe); + int left_interval = pivot_idx_in_inorder - 1 - is; + root.left = buildTree2(inorder, postorder, is, pivot_idx_in_inorder - 1, ps, ps + left_interval); + root.right = buildTree2(inorder, postorder, pivot_idx_in_inorder + 1, ie, ps + left_interval + 1, pe - 1); + return root; + } + + int findSplit2(int[] inorder, int[] postorder, int is, int ie, int ps, int pe) { + int pivot = postorder[pe]; + for (int i = is; i <= ie; ++i) { + if (inorder[i] == pivot) { + return i; + } + } + return -1; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/InorderTraversal.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/InorderTraversal.java new file mode 100644 index 0000000..36eddca --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/InorderTraversal.java @@ -0,0 +1,44 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; + +public class InorderTraversal { + /** + * @param root: The root of binary tree. + * @return: Inorder in ArrayList which contains node values. + */ + public ArrayList inorderTraversal(TreeNode root) { + ArrayList result = new ArrayList(); + inorderTraversal(root, result); + return result; + } + + void inorderTraversal(TreeNode root, ArrayList result) { + if(root == null){ + return; + } + inorderTraversal(root.left, result); + result.add(root.val); + inorderTraversal(root.right, result); + } + + /** + * @param root: The root of binary tree. + * @return: Preorder in ArrayList which contains node values. + */ + public ArrayList preorderTraversal(TreeNode root) { + ArrayList result = new ArrayList(); + preorderTraversal(root, result); + return result; + } + + void preorderTraversal(TreeNode root, ArrayList result) { + if(root == null){ + return; + } + result.add(root.val); + preorderTraversal(root.left, result); + preorderTraversal(root.right, result); + } + +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/InsertNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/InsertNode.java new file mode 100644 index 0000000..db1a557 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/InsertNode.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class InsertNode { + /** + * @param root: + * The root of the binary search tree. + * @param node: + * insert this node into the binary search tree + * @return: The root of the new binary search tree. + */ + public TreeNode insertNode(TreeNode root, TreeNode node) { + TreeNode temp = root; + if(temp == null){ + return node; + } + while (true) { + if (temp.val >= node.val) { + if (temp.left == null) { + temp.left = node; + break; + } else { + temp = temp.left; + } + } else { + if (temp.right == null) { + temp.right = node; + break; + } else { + temp = temp.right; + } + } + } + + return root; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/IsBalanced.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/IsBalanced.java new file mode 100644 index 0000000..1b72425 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/IsBalanced.java @@ -0,0 +1,32 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class IsBalanced { + /** + * @param root: + * The root of binary tree. + * @return: True if this Binary tree is Balanced, or false. + */ + public boolean isBalanced(TreeNode root) { + return getDiff(root) != -1; + } + + int getDiff(TreeNode root) { + if (root == null) { + return 0; + } + int left = getDiff(root.left); + if (left == -1) { + return -1; + } + int right = getDiff(root.right); + if (right == -1) { + return -1; + } + + if (Math.abs(left - right) > 1) { + return -1; + } else { + return 1 + Math.max(left, right); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/IsValidBST.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/IsValidBST.java new file mode 100644 index 0000000..e5870c4 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/IsValidBST.java @@ -0,0 +1,23 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class IsValidBST { + /** + * @param root: + * The root of binary tree. + * @return: True if the binary tree is BST, or false + */ + public boolean isValidBST(TreeNode root) { + return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + boolean isValidBST(TreeNode root, long min, long max) { + if (root == null) { + return true; + } else if (root.val <= min || root.val >= max) { + return false; + } + + return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max); + } + +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/LevelOrder.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/LevelOrder.java new file mode 100644 index 0000000..666bc3b --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/LevelOrder.java @@ -0,0 +1,46 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class LevelOrder { + /** + * @param root: + * The root of binary tree. + * @return: Level order a list of lists of integer + */ + public ArrayList> levelOrder(TreeNode root) { + ArrayList> results = new ArrayList<>(); + if (root == null) { + return results; + } + + Queue q = new LinkedList<>(); + q.add(root); + int cur_cnt = 1; + int next_cnt = 0; + ArrayList result = new ArrayList<>(); + while (!q.isEmpty()) { + TreeNode temp = q.poll(); + --cur_cnt; + result.add(temp.val); + if (temp.left != null) { + q.add(temp.left); + ++next_cnt; + } + if (temp.right != null) { + q.add(temp.right); + ++next_cnt; + } + if (cur_cnt == 0) { + cur_cnt = next_cnt; + next_cnt = 0; + results.add(result); + result = new ArrayList<>(); + } + } + + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/LevelOrderBottom.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/LevelOrderBottom.java new file mode 100644 index 0000000..e598e58 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/LevelOrderBottom.java @@ -0,0 +1,44 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class LevelOrderBottom { + /** + * @param root: + * The root of binary tree. + * @return: buttom-up level order a list of lists of integer + */ + public ArrayList> levelOrderBottom(TreeNode root) { + ArrayList> results = new ArrayList<>(); + if (root == null) { + return results; + } + Queue q = new LinkedList<>(); + q.add(root); + int cur_cnt = 1; + int next_cnt = 0; + ArrayList result = new ArrayList<>(); + while (!q.isEmpty()) { + TreeNode temp = q.poll(); + --cur_cnt; + result.add(temp.val); + if (temp.left != null) { + q.add(temp.left); + ++next_cnt; + } + if (temp.right != null) { + q.add(temp.right); + ++next_cnt; + } + if (cur_cnt == 0) { + cur_cnt = next_cnt; + next_cnt = 0; + results.add(0, result); + result = new ArrayList<>(); + } + } + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/MaxDepth.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/MaxDepth.java new file mode 100644 index 0000000..d18feac --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/MaxDepth.java @@ -0,0 +1,17 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class MaxDepth { + /** + * @param root: + * The root of binary tree. + * @return: An integer. + */ + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + int left = maxDepth(root.left); + int right = maxDepth(root.right); + return Math.max(left, right) + 1; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/MinDepth.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/MinDepth.java new file mode 100644 index 0000000..aebcba4 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/MinDepth.java @@ -0,0 +1,32 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class MinDepth { + /** + * @param root: + * The root of binary tree. + * @return: An integer. + */ + public int minDepth(TreeNode root) { + if (root == null) { + return 0; + } else { + return getMinDepth(root); + } + } + + int getMinDepth(TreeNode root) { + if (root == null) { + return Integer.MAX_VALUE; + }else if(root.left == null && root.right == null){ + return 1; + } + int left = getMinDepth(root.left); + int right = getMinDepth(root.right); + int min = Math.min(left, right); + if (min == Integer.MAX_VALUE) { + return 1; + } else { + return 1 + min; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/NumTrees.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/NumTrees.java new file mode 100644 index 0000000..3845336 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/NumTrees.java @@ -0,0 +1,23 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class NumTrees { + /** + * @paramn n: An integer + * @return: An integer + */ + public int numTrees(int n) { + int[] tab = new int[1 + n]; + tab[0] = 1; + tab[1] = 1; + for (int i = 2; i <= n; ++i) { + int cnt = 0; + for (int left = 0; left <= n; ++left) { + int right = n - left; + cnt += tab[left] * tab[right]; + } + tab[i] = cnt; + } + + return tab[n]; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/PreorderTraversal.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/PreorderTraversal.java new file mode 100644 index 0000000..b10df41 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/PreorderTraversal.java @@ -0,0 +1,25 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; + +public class PreorderTraversal { + /** + * @param root: + * The root of binary tree. + * @return: Preorder in ArrayList which contains node values. + */ + public ArrayList preorderTraversal(TreeNode root) { + if (root == null) { + return new ArrayList<>(); + } + + ArrayList result = new ArrayList<>(); + result.add(root.val); + + ArrayList left = preorderTraversal(root.left), right = preorderTraversal(root.right); + result.addAll(left); + result.addAll(right); + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/SearchRange.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/SearchRange.java new file mode 100644 index 0000000..eaa2911 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/SearchRange.java @@ -0,0 +1,62 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.Queue; + +public class SearchRange { + /** + * @param root: + * The root of the binary search tree. + * @param k1 + * and k2: range k1 to k2. + * @return: Return all keys that k1<=key<=k2 in ascending order. + */ + public ArrayList searchRange(TreeNode root, int k1, int k2) { + ArrayList result = new ArrayList<>(); + if (root == null) { + return result; + } + + Queue q = new LinkedList<>(); + q.add(root); + while (!q.isEmpty()) { + TreeNode temp = q.poll(); + if (temp.val >= k1 && temp.val <= k2) { + result.add(temp.val); + } + if (temp.val > k1 && temp.left != null) { + q.add(temp.left); + } + if (temp.val < k2 && temp.right != null) { + q.add(temp.right); + } + } + + Collections.sort(result); + return result; + } + + public ArrayList searchRangeDFS(TreeNode root, int k1, int k2) { + ArrayList result = new ArrayList<>(); + dfs(root, k1, k2, result); + return result; + } + + void dfs(TreeNode root, int k1, int k2, ArrayList result) { + if (root == null) { + return; + } + + if (root.val > k1) { + dfs(root.left, k1, k2, result); + } + if (root.val >= k1 && root.val <= k2) { + result.add(root.val); + } + if (root.val < k2) { + dfs(root.right, k1, k2, result); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/Serialize.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/Serialize.java new file mode 100644 index 0000000..7049d50 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/Serialize.java @@ -0,0 +1,98 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class Serialize { + /** + * This method will be invoked first, you should design your own algorithm + * to serialize a binary tree which denote by a root node to a string which + * can be easily deserialized by your own "deserialize" method later. + */ + public String serialize(TreeNode root) { + ArrayList temp_list = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.add(root); + while (!q.isEmpty()) { + TreeNode temp = q.poll(); + temp_list.add(temp); + if (temp != null) { + if (temp.left != null) { + q.add(temp.left); + } else { + q.add(null); + } + if (temp.right != null) { + q.add(temp.right); + } else { + q.add(null); + } + } + } + for (int i = temp_list.size() - 1; i >= 0; --i) { + if (temp_list.get(i) == null) { + temp_list.remove(temp_list.size() - 1); + } else { + break; + } + } + StringBuilder sb = new StringBuilder(); + sb.append("{"); + for (int i = 0; i < temp_list.size(); ++i) { + if (temp_list.get(i) == null) { + sb.append("#"); + } else { + sb.append(temp_list.get(i).val); + } + if (i < temp_list.size() - 1) { + sb.append(","); + } + } + sb.append("}"); + return sb.toString(); + } + + /** + * This method will be invoked second, the argument data is what exactly you + * serialized at method "serialize", that means the data is not given by + * system, it's given by your own serialize method. So the format of data is + * designed by yourself, and deserialize it here as you serialize it in + * "serialize" method. + */ + public TreeNode deserialize(String data) { + if (data.equals("{}")) { + return null; + } + String[] nodes = data.substring(1, data.length() - 1).split(","); + if (nodes.length == 0) { + return null; + } else { + Queue q = new LinkedList<>(); + boolean is_left = true; + TreeNode head = new TreeNode(Integer.parseInt(nodes[0])); + q.add(head); + for (int i = 1; i < nodes.length; ++i) { + String node = nodes[i]; + TreeNode temp = null; + if (!node.equals("#")) { + temp = new TreeNode(Integer.parseInt(node)); + } + if (!q.isEmpty()) { + TreeNode parent = q.peek(); + if (is_left) { + parent.left = temp; + } else { + parent.right = temp; + q.poll(); + } + is_left = !is_left; + } + if (temp != null) { + q.add(temp); + } + } + return head; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/TreeNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/TreeNode.java new file mode 100644 index 0000000..fca5178 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/TreeNode.java @@ -0,0 +1,11 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +public class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/ZigzagLevelOrder.java b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/ZigzagLevelOrder.java new file mode 100644 index 0000000..3bd1cd8 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/BinaryTreeLadder/ZigzagLevelOrder.java @@ -0,0 +1,51 @@ +package Lintcode.Base.Ladders.BinaryTreeLadder; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class ZigzagLevelOrder { + /** + * @param root: + * The root of binary tree. + * @return: A list of lists of integer include the zigzag level order + * traversal of its nodes' values + */ + public ArrayList> zigzagLevelOrder(TreeNode root) { + ArrayList> results = new ArrayList<>(); + if (root == null) { + return results; + } + boolean is_order = true; + Queue q = new LinkedList<>(); + q.add(root); + int cur_cnt = 1; + int next_cnt = 0; + ArrayList result = new ArrayList<>(); + while (!q.isEmpty()) { + TreeNode temp = q.poll(); + --cur_cnt; + if (is_order) { + result.add(temp.val); + } else { + result.add(0, temp.val); + } + if (temp.left != null) { + q.add(temp.left); + ++next_cnt; + } + if (temp.right != null) { + q.add(temp.right); + ++next_cnt; + } + if (cur_cnt == 0) { + cur_cnt = next_cnt; + next_cnt = 0; + results.add(result); + result = new ArrayList<>(); + is_order = !is_order; + } + } + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/LargestRectangleArea.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/LargestRectangleArea.java new file mode 100644 index 0000000..7467c58 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/LargestRectangleArea.java @@ -0,0 +1,40 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.Stack; + +public class LargestRectangleArea { + /** + * @param height: + * A list of integer + * @return: The area of largest rectangle in the histogram + */ + public int largestRectangleArea(int[] height) { + if (height == null || height.length == 0) { + return 0; + } + + Stack stack = new Stack<>(); + stack.push(0); + int max_area = height[0]; + for (int i = 1; i < height.length; ++i) { + if (height[i] >= height[i - 1]) { + stack.push(i); + } else { + while (!stack.isEmpty() && height[stack.peek()] > height[i]) { + int h = height[stack.pop()]; + int w = stack.isEmpty() ? i : (i - 1 - stack.peek()); + max_area = Math.max(max_area, h * w); + } + stack.push(i); + } + } + + while (!stack.isEmpty()) { + int h = height[stack.pop()]; + int w = stack.isEmpty() ? (height.length) : (height.length - 1 - stack.peek()); + max_area = Math.max(max_area, h * w); + } + + return max_area; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/ListNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/ListNode.java new file mode 100644 index 0000000..101f52f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/ListNode.java @@ -0,0 +1,11 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +public class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/LongestConsecutive.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/LongestConsecutive.java new file mode 100644 index 0000000..070bee8 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/LongestConsecutive.java @@ -0,0 +1,38 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.HashSet; + +public class LongestConsecutive { + /** + * @param nums: + * A list of integers + * @return an integer + */ + public int longestConsecutive(int[] num) { + int long_len = 0; + HashSet checker = new HashSet<>(); + for (int n : num) { + checker.add(n); + } + + for (int n : num) { + int len = 1; + int loop = n - 1; + while (checker.contains(loop)) { + checker.remove(loop); + loop -= 1; + ++len; + } + loop = n + 1; + while (checker.contains(loop)) { + checker.remove(loop); + loop += 1; + ++len; + } + + long_len = Math.max(long_len, len); + } + + return long_len; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MedianII.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MedianII.java new file mode 100644 index 0000000..78e5251 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MedianII.java @@ -0,0 +1,39 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.Collections; +import java.util.PriorityQueue; + +public class MedianII { + /** + * @param nums: + * A list of integers. + * @return: the median of numbers + */ + public int[] medianII(int[] nums) { + int[] result = new int[nums.length]; + result[0] = nums[0]; + + PriorityQueue max_heap = new PriorityQueue<>(1, Collections.reverseOrder()), min_heap = new PriorityQueue<>(); + + for (int i = 1; i < nums.length; ++i) { + int num = nums[i]; + + if (num >= result[i - 1]) { + min_heap.add(num); + } else { + max_heap.add(num); + } + result[i] = result[i - 1]; + while (1 + max_heap.size() < min_heap.size()) { + max_heap.add(result[i]); + result[i] = min_heap.poll(); + } + while (max_heap.size() > min_heap.size()) { + min_heap.add(result[i]); + result[i] = max_heap.poll(); + } + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MergeKLists.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MergeKLists.java new file mode 100644 index 0000000..db8863e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MergeKLists.java @@ -0,0 +1,48 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +public class MergeKLists { + /** + * @param lists: + * a list of ListNode + * @return: The head of one sorted list. + */ + public ListNode mergeKLists(List lists) { + if (lists == null || lists.size() == 0) { + return null; + } + + PriorityQueue pq = new PriorityQueue(lists.size(), new ListNodeComparator()); + for (ListNode node : lists) { + if (node != null) { + pq.add(node); + } + } + + ListNode pre_head = new ListNode(-1), loop = pre_head; + + while (!pq.isEmpty()) { + ListNode temp = pq.poll(); + if (temp.next != null) { + pq.add(temp.next); + } + if(temp != null){ + loop.next = temp; + loop = loop.next; + } + } + + return pre_head.next; + } + + class ListNodeComparator implements Comparator { + + @Override + public int compare(ListNode o1, ListNode o2) { + return o1.val - o2.val; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MinStack.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MinStack.java new file mode 100644 index 0000000..35fe40c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/MinStack.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.Stack; + +public class MinStack { + + Stack stack = null, stack_min = null; + + public MinStack() { + stack = new Stack<>(); + stack_min = new Stack<>(); + } + + public void push(int number) { + stack.push(number); + int cur_min = min(); + if (cur_min > number) { + stack_min.push(number); + } else { + stack_min.push(cur_min); + } + } + + public int pop() { + stack_min.pop(); + return stack.pop(); + } + + public int min() { + if(stack_min.isEmpty()){ + return Integer.MAX_VALUE; + }else{ + return stack_min.peek(); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/NthUglyNumber.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/NthUglyNumber.java new file mode 100644 index 0000000..5b6fb7f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/NthUglyNumber.java @@ -0,0 +1,63 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.HashSet; +import java.util.PriorityQueue; + +public class NthUglyNumber { + /** + * @param n + * an integer + * @return the nth prime number as description. + */ + public int nthUglyNumber(int n) { + if (n == 1) { + return 1; + } + + HashSet check = new HashSet<>(); + PriorityQueue pq = new PriorityQueue<>(); + long last = 1; + check.add(1l); + for (int i = 1; i < n; ++i) { + if (!check.contains(last * 2)) { + pq.add(last * 2); + check.add(last * 2); + } + if (!check.contains(last * 3)) { + pq.add(last * 3); + check.add(last * 3); + } + if (!check.contains(last * 5)) { + pq.add(last * 5); + check.add(last * 5); + } + + last = pq.poll(); + } + + return (int) last; + } + + public int nthUglyNumber2(int n) { + int[] nums = new int[n]; + nums[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + + for (int i = 1; i < n; ++i) { + int last = nums[i - 1]; + while (2 * nums[p2] <= last) { + ++p2; + } + while (3 * nums[p3] <= last) { + ++p3; + } + while (5 * nums[p5] <= last) { + ++p5; + } + + nums[i] = Math.min(Math.min(5 * nums[p5], 3 * nums[p3]), 2 * nums[p2]); + } + + return nums[n - 1]; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/Queue.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/Queue.java new file mode 100644 index 0000000..87bd2dd --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/Queue.java @@ -0,0 +1,35 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.Stack; + +public class Queue { + private Stack stack1; + private Stack stack2; + + public Queue() { + stack1 = new Stack(); + stack2 = new Stack(); + } + + public void push(int element) { + stack1.push(element); + } + + public int pop() { + if (stack2.isEmpty()) { + while (!stack1.isEmpty()) { + stack2.push(stack1.pop()); + } + } + return stack2.pop(); + } + + public int top() { + if (stack2.isEmpty()) { + while (!stack1.isEmpty()) { + stack2.push(stack1.pop()); + } + } + return stack2.peek(); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/WordSearchII.java b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/WordSearchII.java new file mode 100644 index 0000000..e7004fd --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/DataStructureLadder/WordSearchII.java @@ -0,0 +1,106 @@ +package Lintcode.Base.Ladders.DataStructureLadder; + +import java.util.ArrayList; +import java.util.HashMap; + +public class WordSearchII { + /** + * @param board: + * A list of lists of character + * @param words: + * A list of string + * @return: A list of string + */ + public ArrayList wordSearchII(char[][] board, ArrayList words) { + ArrayList result = new ArrayList<>(); + + Trie trie = new Trie(); + for (String word : words) { + trie.addWord(word); + } + + boolean[][] checker = new boolean[board.length][board[0].length]; + + for (int i = 0; i < board.length; ++i) { + for (int j = 0; j < board[0].length; ++j) { + StringBuilder sb = new StringBuilder(); + dfs(trie.root, result, i, j, board, checker, sb); + } + } + + return result; + } + + void dfs(TrieNode node, ArrayList result, int i, int j, char[][] board, boolean[][] checker, + StringBuilder sb) { + if (i < 0 || j < 0 || i >= board.length || j >= board[0].length) { + return; + } + + if (!checker[i][j] && node.children.containsKey(board[i][j])) { + checker[i][j] = true; + sb.append(board[i][j]); + + TrieNode nnode = node.children.get(board[i][j]); + + if (nnode.isWord && !result.contains(sb.toString())) { + result.add(sb.toString()); + } + + dfs(nnode, result, i + 1, j, board, checker, sb); + dfs(nnode, result, i - 1, j, board, checker, sb); + dfs(nnode, result, i, j + 1, board, checker, sb); + dfs(nnode, result, i, j - 1, board, checker, sb); + + checker[i][j] = false; + sb.setLength(sb.length() - 1); + } + } + + class TrieNode { + char ch; + boolean isWord = false; + HashMap children; + + public TrieNode(char ch) { + this.ch = ch; + this.children = new HashMap<>(); + } + } + + class Trie { + public TrieNode root; + + public Trie() { + this.root = new TrieNode('$'); + } + + public void addWord(String word) { + TrieNode node = root; + for (int i = 0; i < word.length(); ++i) { + char ch = word.charAt(i); + if (node.children.containsKey(ch)) { + node = node.children.get(ch); + } else { + TrieNode nnode = new TrieNode(ch); + node.children.put(ch, nnode); + node = nnode; + } + } + node.isWord = true; + } + + public boolean checkWord(String word) { + TrieNode node = root; + for (int i = 0; i < word.length(); ++i) { + char ch = word.charAt(i); + if (node.children.containsKey(ch)) { + node = node.children.get(ch); + } else { + return false; + } + } + return node.isWord; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/FirstMissingPositive.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/FirstMissingPositive.java new file mode 100644 index 0000000..3eabdca --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/FirstMissingPositive.java @@ -0,0 +1,30 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.HashSet; + +public class FirstMissingPositive { + public int firstMissingPositive(int[] A) { + if (A == null || A.length == 0) { + return 1; + } + + int start = 1; + HashSet checker = new HashSet<>(); + for(int i = 0; i < A.length; ++i){ + if(A[i] > 0 && A[i] < start){ + start = A[i]; + } + checker.add(A[i]); + } + + while(true){ + if(checker.contains(start)){ + ++start; + }else{ + break; + } + } + + return start; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/FourSum.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/FourSum.java new file mode 100644 index 0000000..2a0dd9e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/FourSum.java @@ -0,0 +1,43 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; + +public class FourSum { + public ArrayList> fourSum(int[] numbers, int target) { + Arrays.sort(numbers); + + ArrayList> results = new ArrayList<>(); + + for (int i = 0; i < numbers.length; ++i) { + if (i != 0 && numbers[i] == numbers[i - 1]) { + continue; + } + for (int j = i + 1; j < numbers.length; ++j) { + if (j != i + 1 && numbers[j] == numbers[j - 1]) { + continue; + } + int temp_target = target - numbers[i] - numbers[j]; + HashMap checker = new HashMap<>(); + HashSet duplicate_checker = new HashSet<>(); + for (int k = j + 1; k < numbers.length; ++k) { + String duplicate_key = String.valueOf(numbers[k]) + "_" + String.valueOf(temp_target - numbers[k]); + if (checker.containsKey(temp_target - numbers[k]) && !duplicate_checker.contains(duplicate_key)) { + ArrayList result = new ArrayList(); + result.add(numbers[i]); + result.add(numbers[j]); + result.add(temp_target - numbers[k]); + result.add(numbers[k]); + results.add(result); + duplicate_checker.add(duplicate_key); + } + checker.put(numbers[k], k); + } + } + } + + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/MergeSortedArray.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/MergeSortedArray.java new file mode 100644 index 0000000..402e2b4 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/MergeSortedArray.java @@ -0,0 +1,51 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +public class MergeSortedArray { + /** + * @param A: + * sorted integer array A which has m elements, but size of A is + * m+n + * @param B: + * sorted integer array B which has n elements + * @return: void + */ + public void mergeSortedArray(int[] A, int m, int[] B, int n) { + int i = m - 1, j = n -1, k = m + n - 1; + while (i >= 0 && j >= 0) { + if (A[i] >= B[j]) { + A[k--] = A[i--]; + } else { + A[k--] = B[j--]; + } + } + while(j >= 0){ + A[k--] = B[j--]; + } + } + + /** + * @param A + * and B: sorted integer array A and B. + * @return: A new sorted integer array + */ + public int[] mergeSortedArray(int[] A, int[] B) { + int[] result = new int[A.length + B.length]; + + int i = 0, j = 0, k = 0; + while (i < A.length && j < B.length) { + if (A[i] <= B[j]) { + result[k++] = A[i++]; + } else { + result[k++] = B[j++]; + } + } + while (i < A.length) { + result[k++] = A[i++]; + } + while (j < B.length) { + result[k++] = B[j++]; + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/PartitionArray.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/PartitionArray.java new file mode 100644 index 0000000..22580e5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/PartitionArray.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +public class PartitionArray { + /** + * @param nums: + * The integer array you should partition + * @param k: + * As description return: The index after partition + */ + public int partitionArray(int[] nums, int k) { + if (nums == null || nums.length == 0) { + return 0; + } + + int start = 0, end = nums.length - 1; + while (start <= end) { + while (start <= end && nums[start] < k) { + ++start; + } + + while (start <= end && nums[end] >= k) { + --end; + } + + if (start <= end && start < nums.length && end >= 0 && start != end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + ++start; + --end; + } + } + + return start; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ProductExcludeItself.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ProductExcludeItself.java new file mode 100644 index 0000000..0bb49ec --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ProductExcludeItself.java @@ -0,0 +1,42 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.ArrayList; + +public class ProductExcludeItself { + /** + * @param A: + * Given an integers array A + * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * + * A[n-1] + */ + public ArrayList productExcludeItself(ArrayList A) { + ArrayList result = new ArrayList<>(); + if(A.size() == 1){ + result.add(1l); + return result; + } + long[] left_product = new long[A.size()], right_product = new long[A.size()]; + long base = 1l; + for (int i = 0; i < A.size(); ++i) { + base *= A.get(i); + left_product[i] = base; + } + base = 1; + for (int i = A.size() - 1; i >= 0; --i) { + base *= A.get(i); + right_product[i] = base; + } + + + for (int i = 0; i < A.size(); ++i) { + if (i == 0) { + result.add(right_product[i + 1]); + } else if (i == A.size() - 1) { + result.add(left_product[i - 1]); + } else { + result.add(left_product[i - 1] * right_product[i + 1]); + } + } + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/RemoveDuplicates.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/RemoveDuplicates.java new file mode 100644 index 0000000..4c33386 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/RemoveDuplicates.java @@ -0,0 +1,64 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +public class RemoveDuplicates { + /** + * @param A: a array of integers + * @return : return an integer + */ + public int removeDuplicates(int[] A) { + if (A == null || A.length == 0) { + return 0; + } + + int loop_idx = 0, true_idx = 0; + while(loop_idx < A.length){ + if(loop_idx != true_idx){ + A[true_idx] = A[loop_idx]; + } + int val = A[loop_idx]; + ++true_idx; + ++loop_idx; + while(loop_idx < A.length && A[loop_idx] == val){ + ++loop_idx; + } + } + + return true_idx; + } + + + /** + * @param A: a array of integers + * @return : return an integer + */ + public int removeDuplicates2(int[] nums) { + if(nums == null){ + return 0; + } + + int loop_idx = 0, true_idx = 0; + while(loop_idx < nums.length){ + int val = nums[loop_idx]; + if(loop_idx < nums.length && val == nums[loop_idx]){ + if(loop_idx < nums.length && loop_idx != true_idx){ + nums[true_idx] = nums[loop_idx]; + } + loop_idx++; + true_idx++; + } + if(loop_idx < nums.length && val == nums[loop_idx]){ + if(loop_idx < nums.length && loop_idx != true_idx){ + nums[true_idx] = nums[loop_idx]; + } + loop_idx++; + true_idx++; + } + + while(loop_idx < nums.length && val == nums[loop_idx]){ + loop_idx++; + } + } + + return true_idx; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/RemoveElement.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/RemoveElement.java new file mode 100644 index 0000000..575c2bf --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/RemoveElement.java @@ -0,0 +1,32 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +public class RemoveElement { + /** + * @param A: + * A list of integers + * @param elem: + * An integer + * @return: The new length after remove + */ + public int removeElement(int[] A, int elem) { + int true_idx = 0, loop_idx = 0; + while (loop_idx < A.length) { + if (loop_idx != true_idx) { + int temp = A[loop_idx]; + A[loop_idx] = A[true_idx]; + A[true_idx] = temp; + } + + ++loop_idx; + while (loop_idx < A.length && A[loop_idx] == elem) { + ++loop_idx; + } + if(A[true_idx] != elem){ + ++true_idx; + } + + } + + return true_idx; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/SubarraySum.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/SubarraySum.java new file mode 100644 index 0000000..b088f57 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/SubarraySum.java @@ -0,0 +1,45 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.ArrayList; +import java.util.HashMap; + +public class SubarraySum { + /** + * @param nums: + * A list of integers + * @return: A list of integers includes the index of the first number and + * the index of the last number + */ + public ArrayList subarraySum(int[] nums) { + HashMap> checker = new HashMap<>(); + int cnt = 0; + for(int i = 0; i < nums.length; ++i){ + cnt += nums[i]; + if(!checker.containsKey(cnt)){ + checker.put(cnt, new ArrayList()); + } + checker.get(cnt).add(i); + } + + ArrayList result = new ArrayList<>(); + + if(checker.containsKey(0)){ + result.add(0); + result.add(checker.get(0).get(0)); + return result; + } + + for(int cnt_temp : checker.keySet()){ + ArrayList idx_list = checker.get(cnt_temp); + if(idx_list.size() >= 2){ + for(int i = idx_list.size() - 1; i >= 1; --i){ + result.add(idx_list.get(i - 1) + 1); + result.add(idx_list.get(i)); + return result; + } + } + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/SubarraySumClosest.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/SubarraySumClosest.java new file mode 100644 index 0000000..52f3e92 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/SubarraySumClosest.java @@ -0,0 +1,69 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.ArrayList; +import java.util.Collections; + +public class SubarraySumClosest { + /** + * @param nums: A list of integers + * @return: A list of integers includes the index of the first number + * and the index of the last number + */ + class Pair implements Comparable{ + public int idx, num; + + public Pair(int idx, int num){ + this.idx = idx; + this.num = num; + } + + @Override + public int compareTo(Object o) { + Pair p = (Pair)o; + return p.num - this.num; + } + } + + public int[] subarraySumClosest(int[] nums) { + int[] result = new int[2]; + if (nums == null || nums.length == 0) { + return result; + }else if(nums.length == 1){ + result[0] = result[1] = 0; + return result; + } + + ArrayList pairs = new ArrayList<>(nums.length + 1); + pairs.add(new Pair(0, 0)); + int cnt = 0; + for (int i = 0; i < nums.length; ++i){ + cnt += nums[i]; + pairs.add(new Pair(1 + i, cnt)); + } + + Collections.sort(pairs); + + int min_diff = Integer.MAX_VALUE, min_left = -1, min_right = -1; + for(int i = 1; i < pairs.size(); ++i){ + int diff = Math.abs(pairs.get(i).num - pairs.get(i - 1).num); + if(diff < min_diff){ + min_diff = diff; + min_left = pairs.get(i).idx - 1; + min_right = pairs.get(i - 1).idx - 1; + } + } + + if(min_left > min_right){ + int temp = min_left; + min_left = min_right; + min_right = temp; + } + + + result[0] = 1 + min_left; + result[1] = min_right; + return result; + } + + +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ThreeSum.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ThreeSum.java new file mode 100644 index 0000000..cbc1c15 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ThreeSum.java @@ -0,0 +1,46 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.ArrayList; +import java.util.Arrays; + +public class ThreeSum { + /** + * @param numbers + * : Give an array numbers of n integer + * @return : Find all unique triplets in the array which gives the sum of + * zero. + */ + public ArrayList> threeSum(int[] numbers) { + ArrayList> results = new ArrayList<>(); + + Arrays.sort(numbers); + for (int k = 0; k < numbers.length; ++k) { + if(k != 0 && numbers[k] == numbers[k - 1]){ + continue; + } + int target = -numbers[k], i = k + 1, j = numbers.length - 1; + while (i < j) { + if(i != k + 1 && numbers[i] == numbers[i - 1]){ + ++i; + continue; + } + + if (numbers[i] + numbers[j] == target) { + ArrayList result = new ArrayList<>(); + result.add(numbers[k]); + result.add(numbers[i]); + result.add(numbers[j]); + results.add(result); + ++i; + --j; + } else if (numbers[i] + numbers[j] < target) { + ++i; + } else { + --j; + } + } + } + + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ThreeSumClosest.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ThreeSumClosest.java new file mode 100644 index 0000000..783bb5c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/ThreeSumClosest.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.Arrays; + +public class ThreeSumClosest { + /** + * @param numbers: + * Give an array numbers of n integer + * @param target + * : An integer + * @return : return the sum of the three integers, the sum closest target. + */ + public int threeSumClosest(int[] numbers, int target) { + int closest = Integer.MAX_VALUE; + int sum = Integer.MAX_VALUE - target; + + Arrays.sort(numbers); + for (int k = 0; k < numbers.length - 2; ++k) { + int i = k + 1, j = numbers.length - 1; + while (i < j) { + int diff = Math.abs(target - numbers[k] - numbers[i] - numbers[j]); + if (diff < closest) { + closest = diff; + sum = numbers[i] + numbers[j] + numbers[k]; + } + if (numbers[i] + numbers[j] + numbers[k] <= target) { + ++i; + } else { + --j; + } + } + } + + return sum; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/TwoSum.java b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/TwoSum.java new file mode 100644 index 0000000..604639f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/IntegerArrayLadder/TwoSum.java @@ -0,0 +1,27 @@ +package Lintcode.Base.Ladders.IntegerArrayLadder; + +import java.util.Arrays; +import java.util.HashMap; + +public class TwoSum { + /* + * @param numbers : An array of Integer + * + * @param target : target = numbers[index1] + numbers[index2] + * + * @return : [index1 + 1, index2 + 1] (index1 < index2) + */ + public int[] twoSum(int[] numbers, int target) { + HashMap map = new HashMap<>(); + for(int i = 0; i < numbers.length; ++i){ + if(map.containsKey(target - numbers[i])){ + int[] result = new int[2]; + result[0] = 1 + map.get(target - numbers[i]); + result[1] = 1 + i; + return result; + } + map.put(numbers[i], i); + } + return null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/AddLists.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/AddLists.java new file mode 100644 index 0000000..899fd85 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/AddLists.java @@ -0,0 +1,47 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class AddLists { + /** + * @param l1: the first list + * @param l2: the second list + * @return: the sum list of l1 and l2 + */ + public ListNode addLists(ListNode l1, ListNode l2) { + ListNode pre_head = new ListNode(-1), loop = pre_head; + int carry = 0; + while(l1 != null && l2 != null){ + int v1 = l1.val, v2 = l2.val; + int val = (carry + v1 + v2) % 10; + carry = (carry + v1 + v2) / 10; + ListNode temp = new ListNode(val); + loop.next = temp; + loop = loop.next; + l1 = l1.next; + l2 = l2.next; + } + + while(l1 != null){ + int val = (carry + l1.val) % 10; + carry = (carry + l1.val) / 10; + ListNode temp = new ListNode(val); + loop.next = temp; + loop = loop.next; + l1 = l1.next; + } + while(l2 != null){ + int val = (carry + l2.val) % 10; + carry = (carry + l2.val) / 10; + ListNode temp = new ListNode(val); + loop.next = temp; + loop = loop.next; + l2 = l2.next; + } + + if(carry > 0){ + ListNode temp = new ListNode(carry); + loop.next = temp; + } + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/CopyRandomList.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/CopyRandomList.java new file mode 100644 index 0000000..938157d --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/CopyRandomList.java @@ -0,0 +1,83 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +import java.util.HashMap; + +public class CopyRandomList { + /** + * @param head: + * The head of linked list with a random pointer. + * @return: A new head of a deep copy of the list. + */ + public RandomListNode copyRandomList(RandomListNode head) { + if (head == null) { + return null; + } + HashMap map = new HashMap<>(); + RandomListNode loop = head, dhead = new RandomListNode(head.label); + map.put(loop, dhead); + while (loop != null) { + if (!map.containsKey(loop)) { + map.put(loop, new RandomListNode(loop.label)); + } + RandomListNode dloop = map.get(loop); + if (loop.next != null) { + if (!map.containsKey(loop.next)) { + map.put(loop.next, new RandomListNode(loop.next.label)); + } + RandomListNode dloop_next = map.get(loop.next); + dloop.next = dloop_next; + } + if (loop.random != null) { + if (!map.containsKey(loop.random)) { + map.put(loop.random, new RandomListNode(loop.random.label)); + } + RandomListNode dloop_rand = map.get(loop.random); + dloop.random = dloop_rand; + } + + loop = loop.next; + } + + return dhead; + } + + public RandomListNode copyRandomList_noHM(RandomListNode head) { + if (head == null) { + return null; + } + + RandomListNode loop = head; + + //scan next + while (loop != null) { + RandomListNode next = loop.next; + RandomListNode dloop = new RandomListNode(loop.label); + loop.next = dloop; + dloop.next = next; + loop = next; + } + + //scan random + loop = head; + while (loop != null) { + if(loop.random != null){ + loop.next.random = loop.random.next; + } + loop = loop.next.next; + } + + //split + RandomListNode dhead = head.next;; + loop = head; + while (loop != null) { + RandomListNode dloop = loop.next, next = loop.next.next; + if(loop.next.next != null){ + loop.next = loop.next.next; + dloop.next = dloop.next.next; + } + loop = next; + } + + return dhead; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/DeleteDuplicates.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/DeleteDuplicates.java new file mode 100644 index 0000000..8ec3dcf --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/DeleteDuplicates.java @@ -0,0 +1,51 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class DeleteDuplicates { + /** + * @param ListNode + * head is the head of the linked list + * @return: ListNode head of linked list + */ + public static ListNode deleteDuplicates(ListNode head) { + ListNode temp = head, loop = null; + while (temp != null) { + loop = temp.next; + while (loop != null && loop.val == temp.val) { + loop = loop.next; + } + + temp.next = loop; + temp = temp.next; + } + + return head; + + } + + /** + * @param ListNode + * head is the head of the linked list + * @return: ListNode head of the linked list + */ + public static ListNode deleteDuplicates2(ListNode head) { + ListNode pre_head = new ListNode(-1); + pre_head.next = head; + ListNode temp = pre_head; + + while (temp != null) { + if (temp.next != null && temp.next.next != null + && temp.next.val == temp.next.next.val) { + int val = temp.next.val; + ListNode loop = temp.next; + while(loop != null && loop.val == val){ + loop = loop.next; + } + temp.next = loop; + }else{ + temp = temp.next; + } + } + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/DetectCycle.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/DetectCycle.java new file mode 100644 index 0000000..a3412ab --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/DetectCycle.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class DetectCycle { + /** + * @param head: + * The first node of linked list. + * @return: The node where the cycle begins. if there is no cycle, return + * null + */ + public ListNode detectCycle(ListNode head) { + ListNode slow = head, fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + break; + } + } + + if (slow == fast) { + ListNode temp = head; + while (temp != null && slow != null) { + temp = temp.next; + slow = slow.next; + if (temp == slow) { + return temp; + } + } + return null; + + } else { + return null; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/HasCycle.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/HasCycle.java new file mode 100644 index 0000000..5f49661 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/HasCycle.java @@ -0,0 +1,25 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class HasCycle { + /** + * @param head: + * The first node of linked list. + * @return: True if it has a cycle, or false + */ + public boolean hasCycle(ListNode head) { + if (head == null) { + return false; + } + + ListNode slow = head, fast = head; + while (slow != null && fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if(slow == fast){ + return true; + } + } + + return false; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/ListNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/ListNode.java new file mode 100644 index 0000000..fce738a --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/ListNode.java @@ -0,0 +1,11 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/MergeTwoLists.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/MergeTwoLists.java new file mode 100644 index 0000000..865489e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/MergeTwoLists.java @@ -0,0 +1,37 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class MergeTwoLists { + /** + * @param ListNode + * l1 is the head of the linked list + * @param ListNode + * l2 is the head of the linked list + * @return: ListNode head of linked list + */ + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode pre_head = new ListNode(-1); + + ListNode loop1 = l1, loop2 = l2, loop = pre_head; + while(loop1 != null && loop2 != null){ + if(loop1.val <= loop2.val){ + loop.next = loop1; + loop1 = loop1.next; + }else{ + loop.next = loop2; + loop2 = loop2.next; + } + loop = loop.next; + } + while(loop1 != null){ + loop.next = loop1; + loop1 = loop1.next; + loop = loop.next; + } + while(loop2 != null){ + loop.next = loop2; + loop2 = loop2.next; + loop = loop.next; + } + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/NthToLast.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/NthToLast.java new file mode 100644 index 0000000..9786ba5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/NthToLast.java @@ -0,0 +1,22 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class NthToLast { + /** + * @param head: The first node of linked list. + * @param n: An integer. + * @return: Nth to last node of a singly linked list. + */ + ListNode nthToLast(ListNode head, int n) { + ListNode slow = head, fast = head; + for(int i = 0; i < n; ++i){ + fast = fast.next; + } + + while(fast != null){ + fast = fast.next; + slow = slow.next; + } + + return slow; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/Partition.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/Partition.java new file mode 100644 index 0000000..a612fff --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/Partition.java @@ -0,0 +1,34 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class Partition { + /** + * @param head: The first node of linked list. + * @param x: an integer + * @return: a ListNode + */ + public ListNode partition(ListNode head, int x) { + if (head == null) { + return null; + } + + ListNode left_head = new ListNode(-1), right_head = new ListNode(-1); + ListNode temp = head, left_temp = left_head, right_temp = right_head; + while(temp != null){ + if(temp.val < x){ + left_temp.next = temp; + left_temp = left_temp.next; + }else{ + right_temp.next = temp; + right_temp = right_temp.next; + } + + temp = temp.next; + } + + left_temp.next = right_head.next; + right_temp.next = null; + + return left_head.next; + + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RandomListNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RandomListNode.java new file mode 100644 index 0000000..64308e3 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RandomListNode.java @@ -0,0 +1,10 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +class RandomListNode { + int label; + RandomListNode next, random; + + RandomListNode(int x) { + this.label = x; + } +}; \ No newline at end of file diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RemoveNthFromEnd.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RemoveNthFromEnd.java new file mode 100644 index 0000000..1ae80d5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RemoveNthFromEnd.java @@ -0,0 +1,26 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class RemoveNthFromEnd { + ListNode removeNthFromEnd(ListNode head, int n) { + if (head == null || n == 0) { + return null; + } + + ListNode pre_head = new ListNode(-1); + pre_head.next = head; + + ListNode slow = pre_head, fast = pre_head; + for (int i = 0; i < 1 + n; ++i) { + fast = fast.next; + } + + while(fast != null){ + slow = slow.next; + fast = fast.next; + } + + slow.next = slow.next.next; + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/ReorderList.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/ReorderList.java new file mode 100644 index 0000000..b84b013 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/ReorderList.java @@ -0,0 +1,68 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class ReorderList { + /** + * @param head: + * The head of linked list. + * @return: void + */ + public void reorderList(ListNode head) { + if (head == null || head.next == null) { + return; + } + ListNode mid = findMiddle(head); + ListNode right = reverseList(mid.next); + mid.next = null; + head = mergeList(head, right); + } + + ListNode mergeList(ListNode head1, ListNode head2) { + ListNode pre_head = new ListNode(-1); + ListNode loop = pre_head; + while (head1 != null && head2 != null) { + loop.next = head1; + head1 = head1.next; + + loop = loop.next; + + loop.next = head2; + head2 = head2.next; + + loop = loop.next; + } + if (head1 != null) { + loop.next = head1; + } else { + loop.next = head2; + } + + return pre_head.next; + } + + ListNode findMiddle(ListNode head) { + ListNode slow = head, fast = head; + while (slow != null && fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } + + ListNode reverseList(ListNode head) { + if (head == null) { + return null; + } + ListNode pri = head, cur = head.next; + head.next = null; + while (cur != null) { + ListNode nex = cur.next; + + cur.next = pri; + + pri = cur; + cur = nex; + } + + return pri; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/Reverse.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/Reverse.java new file mode 100644 index 0000000..c818b53 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/Reverse.java @@ -0,0 +1,57 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class Reverse { + /** + * @param head: + * The head of linked list. + * @return: The new head of reversed linked list. + */ + public ListNode reverse(ListNode head) { + if (head == null) { + return null; + } + + ListNode pri = head, cur = head.next; + head.next = null; + while (cur != null) { + ListNode nex = cur.next; + + cur.next = pri; + + pri = cur; + cur = nex; + } + + return pri; + } + + /** + * @param ListNode + * head is the head of the linked list + * @oaram m and n + * @return: The head of the reversed ListNode + */ + public ListNode reverseBetween(ListNode head, int m, int n) { + ListNode pre_head = new ListNode(0); + pre_head.next = head; + + ListNode pri = pre_head; + for(int i = 0; i < m - 1; ++i){ + pri = pri.next; + } + ListNode left1 = pri; + pri = pri.next; + ListNode left2 = pri; + ListNode cur = pri.next; + for(int i = m; i < n; ++i){ + ListNode next = cur.next; + cur.next = pri; + pri = cur; + cur = next; + } + left1.next = pri; + left2.next = cur; + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RotateRight.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RotateRight.java new file mode 100644 index 0000000..fb83be6 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/RotateRight.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class RotateRight { + /** + * @param head: the List + * @param k: rotate to the right k places + * @return: the list after rotation + */ + public ListNode rotateRight(ListNode head, int n) { + if (head == null) { + return null; + } + + int cnt = 0; + ListNode loop = head; + while(loop != null){ + loop = loop.next; + ++cnt; + } + n %= cnt; + + ListNode slow = head, fast = head; + for(int i = 0; i < n; ++i){ + fast = fast.next; + } + while(fast.next != null){ + slow = slow.next; + fast = fast.next; + } + fast.next = head; + head = slow.next; + slow.next = null; + + return head; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/SortList.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/SortList.java new file mode 100644 index 0000000..3d0014b --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/SortList.java @@ -0,0 +1,57 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class SortList { + /** + * @param head: The head of linked list. + * @return: You should return the head of the sorted linked list, + using constant space complexity. + */ + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode mid = findMiddle(head); + + ListNode right = sortList(mid.next); + mid.next = null; + ListNode left = sortList(head); + + return mergeList(left, right); + } + + ListNode mergeList(ListNode head1, ListNode head2) { + ListNode pre_head = new ListNode(-1); + ListNode loop = pre_head; + while (head1 != null && head2 != null) { + if(head1.val <= head2.val){ + loop.next = head1; + head1 = head1.next; + }else{ + loop.next = head2; + head2 = head2.next; + } + + loop = loop.next; + } + while (head1 != null) { + loop.next = head1; + head1 = head1.next; + loop = loop.next; + } + while (head2 != null) { + loop.next = head2; + head2 = head2.next; + loop = loop.next; + } + return pre_head.next; + } + + ListNode findMiddle(ListNode head) { + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/SortedListToBSTHelper.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/SortedListToBSTHelper.java new file mode 100644 index 0000000..39b15f4 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/SortedListToBSTHelper.java @@ -0,0 +1,40 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class SortedListToBSTHelper { + /** + * @param head: + * The first node of linked list. + * @return: a tree node + */ + public TreeNode sortedListToBST(ListNode head) { + int length = getLength(head); + temp = head; + return getTreeNode(length); + } + + ListNode temp = null; + + TreeNode getTreeNode(int steps) { + if (steps <= 0) { + return null; + } + TreeNode left_child = getTreeNode(steps / 2); + TreeNode node = new TreeNode(temp.val); + temp = temp.next; + TreeNode right_child = getTreeNode(steps - 1 - steps / 2); + node.left = left_child; + node.right = right_child; + return node; + } + + int getLength(ListNode head) { + int cnt = 0; + ListNode temp = head; + while (temp != null) { + temp = temp.next; + ++cnt; + } + return cnt; + } + +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/TreeNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/TreeNode.java new file mode 100644 index 0000000..64deb6d --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/LinkedListLadder/TreeNode.java @@ -0,0 +1,11 @@ +package Lintcode.Base.Ladders.LinkedListLadder; + +public class TreeNode { + public int val; + public TreeNode left, right; + + public TreeNode(int val) { + this.val = val; + this.left = this.right = null; + } +} \ No newline at end of file diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CloneGraph.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CloneGraph.java new file mode 100644 index 0000000..28e2cd9 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CloneGraph.java @@ -0,0 +1,42 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Queue; + +public class CloneGraph { + /** + * @param node: + * A undirected graph node + * @return: A undirected graph node + */ + public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { + if (node == null) { + return null; + } + UndirectedGraphNode nnode = new UndirectedGraphNode(node.label); + HashMap map = new HashMap<>(); + Queue q = new LinkedList<>(); + + q.add(node); + map.put(node, nnode); + while (!q.isEmpty()) { + UndirectedGraphNode temp = q.poll(); + if(!map.containsKey(temp)){ + map.put(temp, new UndirectedGraphNode(temp.label)); + } + UndirectedGraphNode ntemp = map.get(temp); + + for(UndirectedGraphNode temp_loop : temp.neighbors){ + if(!map.containsKey(temp_loop)){ + map.put(temp_loop, new UndirectedGraphNode(temp_loop.label)); + q.add(temp_loop); + } + UndirectedGraphNode ntemp_loop = map.get(temp_loop); + ntemp.neighbors.add(ntemp_loop); + } + } + + return nnode; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CombinationSum.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CombinationSum.java new file mode 100644 index 0000000..072e716 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CombinationSum.java @@ -0,0 +1,42 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CombinationSum { + /** + * @param candidates: + * A list of integers + * @param target:An + * integer + * @return: A list of lists of integers + */ + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + List> results = new ArrayList<>(); + dfs(candidates, target, results, new ArrayList(), 0); + return results; + } + + void dfs(int[] candidates, int target, List> results, List result, int cur_i) { + if (target == 0) { + results.add(new ArrayList(result)); + return; + } else if (target < 0) { + return; + } + + int pre = -1; + for (int i = cur_i; i < candidates.length; ++i) { + if (pre != -1 && pre == candidates[i]) { + continue; + } + result.add(candidates[i]); + dfs(candidates, target - candidates[i], results, result, i); + result.remove(result.size() - 1); + + pre = candidates[i]; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CombinationSum2.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CombinationSum2.java new file mode 100644 index 0000000..3f65cee --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/CombinationSum2.java @@ -0,0 +1,42 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CombinationSum2 { + /** + * @param num: + * Given the candidate numbers + * @param target: + * Given the target number + * @return: All the combinations that sum to target + */ + public List> combinationSum2(int[] num, int target) { + Arrays.sort(num); + List> results = new ArrayList<>(); + dfs(num, target, results, new ArrayList(), 0); + return results; + } + + void dfs(int[] candidates, int target, List> results, List result, int cur_i) { + if (target == 0) { + results.add(new ArrayList(result)); + return; + } else if (target < 0) { + return; + } + + int pre = -1; + for (int i = cur_i; i < candidates.length; ++i) { + if (pre != -1 && pre == candidates[i]) { + continue; + } + result.add(candidates[i]); + dfs(candidates, target - candidates[i], results, result, 1 + i); + result.remove(result.size() - 1); + + pre = candidates[i]; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Combine.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Combine.java new file mode 100644 index 0000000..ee91f00 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Combine.java @@ -0,0 +1,32 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.List; + +public class Combine { + /** + * @param n: + * Given the range of numbers + * @param k: + * Given the numbers of combinations + * @return: All the combinations of k numbers out of 1..n + */ + public List> combine(int n, int k) { + List> results = new ArrayList<>(); + dfs(n, k, results, new ArrayList(), 0); + return results; + } + + void dfs(int n, int k, List> results, List result, int cur_i) { + if (result.size() == k) { + results.add(new ArrayList(result)); + return; + } + + for (int i = 1 + cur_i; i <= n; ++i) { + result.add(i); + dfs(n, k, results, result, i); + result.remove(result.size() - 1); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/DirectedGraphNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/DirectedGraphNode.java new file mode 100644 index 0000000..8f51a9f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/DirectedGraphNode.java @@ -0,0 +1,13 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; + +class DirectedGraphNode { + int label; + ArrayList neighbors; + + DirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } +}; diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/FindLadders.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/FindLadders.java new file mode 100644 index 0000000..2c14c27 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/FindLadders.java @@ -0,0 +1,85 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Set; + +public class FindLadders { + /** + * @param start, + * a string + * @param end, + * a string + * @param dict, + * a set of string + * @return a list of lists of string + */ + public List> findLadders(String start, String end, Set dict) { + List> results = new ArrayList<>(); + if (dict == null) { + return results; + } + + if (start.equals(end)) { + List result = new ArrayList<>(); + result.add(start); + result.add(end); + results.add(result); + return results; + } + + dict.add(start); + dict.add(end); + + HashSet set = new HashSet<>(); + set.add(start); + + List result = new ArrayList<>(); + result.add(start); + dfs(start, dict, set, result, results, end); + + int min_len = Integer.MAX_VALUE; + for(List temp : results){ + min_len = Math.min(temp.size(), min_len); + } + List> nresults = new ArrayList<>(); + for(List temp : results){ + if(temp.size() == min_len){ + nresults.add(temp); + } + } + + return nresults; + } + + void dfs(String word, Set dict, HashSet set, List result, List> results, String end) { + if(word.equals(end)){ + results.add(new ArrayList<>(result)); + return; + } + for (char c = 'a'; c <= 'z'; c++) { + for (int i = 0; i < word.length(); i++) { + if (c == word.charAt(i)) { + continue; + } + String nextWord = replace(word, i, c); + if (!set.contains(nextWord) && dict.contains(nextWord)) { + result.add(nextWord); + set.add(nextWord); + dfs(nextWord, dict, set, result, results, end); + set.remove(nextWord); + result.remove(result.size() - 1); + } + } + } + } + + private String replace(String s, int index, char c) { + char[] chars = s.toCharArray(); + chars[index] = c; + return new String(chars); + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/LadderLength.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/LadderLength.java new file mode 100644 index 0000000..5267967 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/LadderLength.java @@ -0,0 +1,120 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Set; + +public class LadderLength { + /** + * @param start, + * a string + * @param end, + * a string + * @param dict, + * a set of string + * @return an integer + */ + public int ladderLength(String start, String end, Set dict) { + if (dict == null) { + return 0; + } + + if (start.equals(end)) { + return 1; + } + + dict.add(start); + dict.add(end); + + Queue q = new LinkedList<>(); + HashSet set = new HashSet<>(); + q.offer(start); + set.add(start); + + int length = 1; + while (!q.isEmpty()) { + ++length; + int qsize = q.size(); + for (int i = 0; i < qsize; ++i) { + String temp = q.poll(); + ArrayList next_words = getNextWords(temp, dict,set); + for (String next_word : next_words) { + if (next_word.equals(end)) { + return length; + } + + q.offer(next_word); + set.add(next_word); + } + } + } + + return -1; + } + + ArrayList getNextWords2(String start, Set dict, HashSet set) { + ArrayList words = new ArrayList<>(); + // edit distance + for (String word : dict) { + if (!set.contains(word) && editDist(start, word) == 1) { + words.add(word); + } + } + return words; + } + + int editDist(String word1, String word2) { + int[][] tab = new int[1 + word1.length()][1 + word2.length()]; + + tab[0][0] = 0; + + for (int i = 1; i <= word1.length(); ++i) { + tab[i][0] = tab[i - 1][0] + 1; + + } + for (int i = 1; i <= word2.length(); ++i) { + tab[0][i] = tab[0][i - 1] + 1; + } + + for (int i = 1; i <= word1.length(); ++i) { + for (int j = 1; j <= word2.length(); ++j) { + int base = tab[i - 1][j - 1]; + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + tab[i][j] = base; + } else { + tab[i][j] = base + 1; + } + } + } + return tab[word1.length()][word2.length()]; + } + + // replace character of a string at given index to a given character + // return a new string + private String replace(String s, int index, char c) { + char[] chars = s.toCharArray(); + chars[index] = c; + return new String(chars); + } + + // get connections with given word. + // for example, given word = 'hot', dict = {'hot', 'hit', 'hog'} + // it will return ['hit', 'hog'] + private ArrayList getNextWords(String word, Set dict, HashSet set) { + ArrayList nextWords = new ArrayList(); + for (char c = 'a'; c <= 'z'; c++) { + for (int i = 0; i < word.length(); i++) { + if (c == word.charAt(i)) { + continue; + } + String nextWord = replace(word, i, c); + if (!set.contains(nextWord) && dict.contains(nextWord)) { + nextWords.add(nextWord); + } + } + } + return nextWords; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Permute.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Permute.java new file mode 100644 index 0000000..a8d63c6 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Permute.java @@ -0,0 +1,36 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +public class Permute { + /** + * @param nums: + * A list of integers. + * @return: A list of permutations. + */ + public List> permute(int[] nums) { + Arrays.sort(nums); + List> results = new ArrayList<>(); + dfs(nums, new HashSet(), results, new ArrayList()); + return results; + } + + void dfs(int[] nums, HashSet set, List> results, ArrayList result) { + if(result.size() == nums.length){ + results.add(new ArrayList(result)); + return; + } + for (int i = 0; i < nums.length; ++i) { + if (!set.contains(i)) { + set.add(i); + result.add(nums[i]); + dfs(nums, set, results, result); + result.remove(result.size() - 1); + set.remove(i); + } + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/PermuteUnique.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/PermuteUnique.java new file mode 100644 index 0000000..dc6b40f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/PermuteUnique.java @@ -0,0 +1,43 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +public class PermuteUnique { + /** + * @param nums: + * A list of integers. + * @return: A list of unique permutations. + */ + public List> permuteUnique(int[] nums) { + Arrays.sort(nums); + List> results = new ArrayList<>(); + dfs(nums, new HashSet(), results, new ArrayList()); + return results; + } + + void dfs(int[] nums, HashSet set, List> results, ArrayList result) { + if (result.size() == nums.length) { + results.add(new ArrayList(result)); + return; + } + int pre = -99999; + for (int i = 0; i < nums.length; ++i) { + if (pre != -99999 && pre == nums[i]) { + continue; + } + + if (!set.contains(i)) { + set.add(i); + result.add(nums[i]); + dfs(nums, set, results, result); + result.remove(result.size() - 1); + set.remove(i); + } + + pre = nums[i]; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/SolveNQueens.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/SolveNQueens.java new file mode 100644 index 0000000..28dfbd9 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/SolveNQueens.java @@ -0,0 +1,74 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; + +public class SolveNQueens { + /** + * Get all distinct N-Queen solutions + * + * @param n: + * The number of queens + * @return: All distinct solutions For example, A string '...Q' shows a + * queen on forth position + */ + ArrayList> solveNQueens(int n) { + int[] tab = new int[n]; + for (int i = 0; i < n; ++i) { + tab[i] = -1; + } + ArrayList> results = new ArrayList<>(); + dfs(tab, 0, results); + return results; + } + + void dfs(int[] tab, int row_idx, ArrayList> results) { + if (row_idx == tab.length) { + results.add(getResult(tab)); + } + + for (int col_idx = 0; col_idx < tab.length; ++col_idx) { + if (isValidate(tab, row_idx, col_idx)) { + tab[row_idx] = col_idx; + dfs(tab, row_idx + 1, results); + tab[row_idx] = -1; + } + } + } + + boolean isValidate(int[] tab, int row_idx, int col_idx) { + for (int i = row_idx - 1; i >= 0; --i) { + if (tab[i] == col_idx) { + return false; + } else if (tab[i] == col_idx - 1 - (row_idx - 1 - i)) { + return false; + } else if (tab[i] == col_idx + 1 + (row_idx - 1 - i)) { + return false; + } + } + for (int i = col_idx - 1; i >= 0; --i) { + if (tab[row_idx] == i) { + return false; + } + } + return true; + } + + ArrayList getResult(int[] tab) { + ArrayList result = new ArrayList<>(); + + for (int i = 0; i < tab.length; ++i) { + StringBuilder sb = new StringBuilder(); + int j = 0; + for (; j < tab[i]; ++j) { + sb.append("."); + } + sb.append("Q"); + ++j; + for (; j < tab.length; ++j) { + sb.append("."); + } + result.add(sb.toString()); + } + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Subsets.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Subsets.java new file mode 100644 index 0000000..3216031 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/Subsets.java @@ -0,0 +1,28 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.Arrays; + +public class Subsets { + /** + * @param S: + * A set of numbers. + * @return: A list of lists. All valid subsets. + */ + public ArrayList> subsets(int[] nums) { + Arrays.sort(nums); + ArrayList> results = new ArrayList<>(); + results.add(new ArrayList()); + dfs(nums, 0, results, new ArrayList()); + return results; + } + + void dfs(int[] nums, int cur_i, ArrayList> results, ArrayList result) { + for (int i = cur_i; i < nums.length; ++i) { + result.add(nums[i]); + results.add(new ArrayList(result)); + dfs(nums, i + 1, results, result); + result.remove(result.size() - 1); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/SubsetsWithDup.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/SubsetsWithDup.java new file mode 100644 index 0000000..9834118 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/SubsetsWithDup.java @@ -0,0 +1,34 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; +import java.util.Arrays; + +public class SubsetsWithDup { + /** + * @param nums: + * A set of numbers. + * @return: A list of lists. All valid subsets. + */ + public ArrayList> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + ArrayList> results = new ArrayList<>(); + results.add(new ArrayList()); + dfs(nums, 0, results, new ArrayList()); + return results; + } + + void dfs(int[] nums, int cur_i, ArrayList> results, ArrayList result) { + int pre = -1; + for (int i = cur_i; i < nums.length; ++i) { + if (pre != -1 && pre == nums[i]) { + continue; + } + result.add(nums[i]); + results.add(new ArrayList(result)); + dfs(nums, i + 1, results, result); + result.remove(result.size() - 1); + + pre = nums[i]; + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/TopSort.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/TopSort.java new file mode 100644 index 0000000..1c64719 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/TopSort.java @@ -0,0 +1,42 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; + +public class TopSort { + /** + * @param graph: + * A list of Directed graph node + * @return: Any topological order for the given graph. + */ + public ArrayList topSort(ArrayList graph) { + int[] indegree = new int[graph.size()]; + + for (DirectedGraphNode node : graph) { + for (DirectedGraphNode out_degree_node : node.neighbors) { + ++indegree[out_degree_node.label]; + } + } + + ArrayList result = new ArrayList<>(); + for (int i = 0; i < indegree.length; ++i) { + int idx = updateZeroIndgree(indegree, graph); + result.add(graph.get(idx)); + } + + return result; + } + + int updateZeroIndgree(int[] indegree, ArrayList graph) { + for (int i = 0; i < indegree.length; ++i) { + if (indegree[i] == 0) { + // update indegree + for (DirectedGraphNode out_degree_node : graph.get(i).neighbors) { + --indegree[out_degree_node.label]; + } + indegree[i] = -1; + return i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/TotalNQueens.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/TotalNQueens.java new file mode 100644 index 0000000..50505d7 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/TotalNQueens.java @@ -0,0 +1,71 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; + +public class TotalNQueens { + /** + * Calculate the total number of distinct N-Queen solutions. + * @param n: The number of queens. + * @return: The total number of distinct solutions. + */ + public int totalNQueens(int n) { + int[] tab = new int[n]; + for (int i = 0; i < n; ++i) { + tab[i] = -1; + } + ArrayList> results = new ArrayList<>(); + dfs(tab, 0, results); + return results.size(); + } + + void dfs(int[] tab, int row_idx, ArrayList> results) { + if (row_idx == tab.length) { + results.add(getResult(tab)); + } + + for (int col_idx = 0; col_idx < tab.length; ++col_idx) { + if (isValidate(tab, row_idx, col_idx)) { + tab[row_idx] = col_idx; + dfs(tab, row_idx + 1, results); + tab[row_idx] = -1; + } + } + } + + boolean isValidate(int[] tab, int row_idx, int col_idx) { + for (int i = row_idx - 1; i >= 0; --i) { + if (tab[i] == col_idx) { + return false; + } else if (tab[i] == col_idx - 1 - (row_idx - 1 - i)) { + return false; + } else if (tab[i] == col_idx + 1 + (row_idx - 1 - i)) { + return false; + } + } + for (int i = col_idx - 1; i >= 0; --i) { + if (tab[row_idx] == i) { + return false; + } + } + return true; + } + + ArrayList getResult(int[] tab) { + ArrayList result = new ArrayList<>(); + + for (int i = 0; i < tab.length; ++i) { + StringBuilder sb = new StringBuilder(); + int j = 0; + for (; j < tab[i]; ++j) { + sb.append("."); + } + sb.append("Q"); + ++j; + for (; j < tab.length; ++j) { + sb.append("."); + } + result.add(sb.toString()); + } + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/UndirectedGraphNode.java b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/UndirectedGraphNode.java new file mode 100644 index 0000000..db66758 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/SearchRecursionLadder/UndirectedGraphNode.java @@ -0,0 +1,13 @@ +package Lintcode.Base.Ladders.SearchRecursionLadder; + +import java.util.ArrayList; + +class UndirectedGraphNode { + int label; + ArrayList neighbors; + + UndirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } +}; \ No newline at end of file diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/Anagram.java b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/Anagram.java new file mode 100644 index 0000000..7502342 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/Anagram.java @@ -0,0 +1,29 @@ +package Lintcode.Base.Ladders.StringLadder; + +public class Anagram { + /** + * @param s: The first string + * @param b: The second string + * @return true or false + */ + public boolean anagram(String s, String t) { + if(s == null || t == null || s.length() != t.length()){ + return false; + } + + int[] checker = new int[0XFF]; + for(int i = 0; i < s.length(); ++i){ + char ch = s.charAt(i); + ++checker[ch]; + } + for(int i = 0; i < s.length(); ++i){ + char ch = t.charAt(i); + --checker[ch]; + if(checker[ch] < 0){ + return false; + } + } + + return true; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/Anagrams.java b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/Anagrams.java new file mode 100644 index 0000000..4657819 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/Anagrams.java @@ -0,0 +1,49 @@ +package Lintcode.Base.Ladders.StringLadder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class Anagrams { + /** + * @param strs: + * A list of strings + * @return: A list of strings + */ + + int getHash(String str) { + int h = str.length(); + int[] cnt = new int[26]; + for (int i = 0; i < str.length(); ++i) { + ++cnt[str.charAt(i) - 'a']; + } + for (int i = 0; i < 26; ++i) { + h = h * 26 + cnt[i]; + } + return h; + } + + public List anagrams(String[] strs) { + List result = new ArrayList<>(); + if (strs == null) { + return result; + } + + HashMap> helper = new HashMap<>(); + for(String str : strs){ + int h = getHash(str); + if(!helper.containsKey(h)){ + helper.put(h, new ArrayList()); + } + helper.get(h).add(str); + } + + for(ArrayList temp_list : helper.values()){ + if(temp_list.size() > 1){ + result.addAll(temp_list); + } + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/CompareStrings.java b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/CompareStrings.java new file mode 100644 index 0000000..d0b8995 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/CompareStrings.java @@ -0,0 +1,31 @@ +package Lintcode.Base.Ladders.StringLadder; + +public class CompareStrings { + /** + * @param A : A string includes Upper Case letters + * @param B : A string includes Upper Case letter + * @return : if string A contains all of the characters in B return true else return false + */ + public boolean compareStrings(String A, String B) { + if(A == null || B == null || A.length() < B.length()){ + return false; + } + + int[] checker = new int[0XFF]; + + for(int i = 0; i < A.length(); ++i){ + char ch = A.charAt(i); + ++checker[ch]; + } + + for(int i = 0; i < B.length(); ++i){ + char ch = B.charAt(i); + --checker[ch]; + if(checker[ch] < 0){ + return false; + } + } + + return true; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/LongestCommonPrefix.java b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/LongestCommonPrefix.java new file mode 100644 index 0000000..a0ab1b2 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/LongestCommonPrefix.java @@ -0,0 +1,26 @@ +package Lintcode.Base.Ladders.StringLadder; + +public class LongestCommonPrefix { + /** + * @param strs: A list of strings + * @return: The longest common prefix + */ + public String longestCommonPrefix(String[] strs) { + if(strs == null || strs.length == 0){ + return ""; + } + + int idx = 0; + while(idx < strs[0].length()){ + char ch = strs[0].charAt(idx); + for(int i = 1; i < strs.length; ++i){ + if(idx >= strs[i].length() || strs[i].charAt(idx) != ch){ + return strs[0].substring(0, idx); + } + } + ++idx; + } + + return strs[0]; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/LongestCommonSubstring.java b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/LongestCommonSubstring.java new file mode 100644 index 0000000..e8b7ead --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/LongestCommonSubstring.java @@ -0,0 +1,29 @@ +package Lintcode.Base.Ladders.StringLadder; + +public class LongestCommonSubstring { + /** + * @param A, B: Two string. + * @return: the length of the longest common substring. + */ + public int longestCommonSubstring(String A, String B) { + if(A == null || B == null || A.length() == 0 || B.length() == 0){ + return 0; + } + int max_value = 0; + int[][] tab = new int[1 + A.length()][1 + B.length()]; + + //process tab + for(int i = 1; i <= A.length(); ++i){ + for(int j = 1; j <= B.length(); ++j){ + int val = 0; + if(A.charAt(i - 1) == B.charAt(j - 1)){ + val = 1 + tab[i - 1][j - 1]; + } + tab[i][j] = val; + max_value = Math.max(max_value, val); + } + } + + return max_value; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/StrStr.java b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/StrStr.java new file mode 100644 index 0000000..4368866 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Base/Ladders/StringLadder/StrStr.java @@ -0,0 +1,33 @@ +package Lintcode.Base.Ladders.StringLadder; + +public class StrStr { + /** + * Returns a index to the first occurrence of target in source, + * or -1 if target is not part of source. + * @param source string to be scanned. + * @param target string containing the sequence of characters to match. + */ + public int strStr(String source, String target) { + if(source == null || target == null || source.length() < target.length()){ + return -1; + } + if(target.length() == 0){ + return 0; + } + + int i = 0, j = 0; + for(;i < source.length(); ++i){ + int temp_i = i; + while(temp_i < source.length() && source.charAt(temp_i) == target.charAt(j)){ + ++temp_i; + ++j; + if(target.length() == j){ + return i; + } + } + j = 0; + } + + return -1; + } +} diff --git a/Algorithm-Java/src/Lintcode/Base/Problems.docx b/Algorithm-Java/src/Lintcode/Base/Problems.docx new file mode 100644 index 0000000..b710942 Binary files /dev/null and b/Algorithm-Java/src/Lintcode/Base/Problems.docx differ diff --git a/Algorithm-Java/src/Lintcode/Base/~$oblems.docx b/Algorithm-Java/src/Lintcode/Base/~$oblems.docx new file mode 100644 index 0000000..bd220dc Binary files /dev/null and b/Algorithm-Java/src/Lintcode/Base/~$oblems.docx differ diff --git a/Algorithm-Java/src/Lintcode/Intensive/L1/FourSum.java b/Algorithm-Java/src/Lintcode/Intensive/L1/FourSum.java new file mode 100644 index 0000000..61d835f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L1/FourSum.java @@ -0,0 +1,58 @@ +package Lintcode.Intensive.L1; + +import java.util.ArrayList; +import java.util.Arrays; + +public class FourSum { + /** + * @param numbers + * : Give an array numbersbers of n integer + * @param target + * : you need to find four elements that's sum of target + * @return : Find all unique quadruplets in the array which gives the sum of + * zero. + */ + public ArrayList> fourSum(int[] numbers, int target) { + ArrayList> results = new ArrayList<>(); + Arrays.sort(numbers); + + for (int i = 0; i < numbers.length; i++) { + if (i != 0 && numbers[i] == numbers[i - 1]) { + continue; + } + for (int j = i + 1; j < numbers.length; j++) { + if (j != i + 1 && numbers[j] == numbers[j - 1]) { + continue; + } + int sub_target = target - numbers[i] - numbers[j]; + + int left = j + 1, right = numbers.length - 1; + while (left < right) { + if (numbers[left] + numbers[right] > sub_target) { + --right; + } else if (numbers[left] + numbers[right] < sub_target) { + ++left; + } else { + ArrayList result = new ArrayList<>(); + result.add(numbers[i]); + result.add(numbers[j]); + result.add(numbers[left]); + result.add(numbers[right]); + results.add(result); + left++; + right--; + while (left < right && numbers[left] == numbers[left - 1]) { + left++; + } + while (left < right && numbers[right] == numbers[right + 1]) { + right--; + } + } + } + + } + } + + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L1/KthSmallest.java b/Algorithm-Java/src/Lintcode/Intensive/L1/KthSmallest.java new file mode 100644 index 0000000..8144c96 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L1/KthSmallest.java @@ -0,0 +1,62 @@ +package Lintcode.Intensive.L1; + +import java.util.Comparator; +import java.util.PriorityQueue; + + +public class KthSmallest { + /** + * @param matrix: a matrix of integers + * @param k: an integer + * @return: the kth smallest number in the matrix + */ + class Entry{ + int x; + int y; + int val; + public Entry(int x, int y, int val){ + this.val = val; + this.x = x; + this.y = y; + } + } + + class QueueComp implements Comparator{ + + @Override + public int compare(Entry o1, Entry o2) { + return o1.val - o2.val; + } + + } + + public int kthSmallest(int[][] matrix, int k) { + PriorityQueue queue = new PriorityQueue<>(new QueueComp()); + queue.add(new Entry(0, 0, matrix[0][0])); + + boolean[][] checked = new boolean[matrix.length][matrix[0].length]; + + while (true) { + Entry entry = queue.poll(); + if(--k==0){ + return entry.val; + } + + if(entry.x+1 < matrix.length && !checked[entry.x][entry.y]){ + queue.add(new Entry(entry.x+1, entry.y, matrix[entry.x+1][entry.y])); + checked[entry.x+1][entry.y] = true; + } + if(entry.y+1 < matrix[0].length && !checked[entry.x][entry.y+1]){ + queue.add(new Entry(entry.x, entry.y+1, matrix[entry.x][entry.y+1])); + checked[entry.x][entry.y+1] = true; + } + + } + } + + public static void main(String[] args) { + int[][] matrix = {{1,5,7},{3,7,8},{4,8,9}}; + int value =new KthSmallest().kthSmallest(matrix, 6); + System.out.println(value); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L1/SearchMatrix.java b/Algorithm-Java/src/Lintcode/Intensive/L1/SearchMatrix.java new file mode 100644 index 0000000..0727cb5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L1/SearchMatrix.java @@ -0,0 +1,52 @@ +package Lintcode.Intensive.L1; + +public class SearchMatrix { + /** + * @param matrix, a list of lists of integers + * @param target, an integer + * @return a boolean, indicate whether matrix contains target + */ + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return false; + } + int cnt = 0, m = matrix.length, n = matrix[0].length; + int i = 0, j = n-1; + while (i>=0 && j>=0 && i target) { + --j; + }else if (matrix[i][j] < target) { + ++i; + }else{ + return true; + } + } + return false; + } + + /** + * @param matrix: + * A list of lists of integers + * @param: A + * number you want to search in the matrix + * @return: An integer indicate the occurrence of target in the given matrix + */ + public int searchMatrixCnt(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return 0; + } + int cnt = 0, m = matrix.length, n = matrix[0].length; + int i = 0, j = n-1; + while (i>=0 && j>=0 && i target) { + --j; + }else if (matrix[i][j] < target) { + ++i; + }else{ + cnt++; + --j; + } + } + return cnt; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L1/ThreeSum.java b/Algorithm-Java/src/Lintcode/Intensive/L1/ThreeSum.java new file mode 100644 index 0000000..b2dbb5b --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L1/ThreeSum.java @@ -0,0 +1,44 @@ +package Lintcode.Intensive.L1; + +import java.util.ArrayList; +import java.util.Arrays; + +public class ThreeSum { + /** + * @param numbers : Give an array numbers of n integer + * @return : Find all unique triplets in the array which gives the sum of zero. + */ + public ArrayList> threeSum(int[] numbers) { + ArrayList> solutions = new ArrayList>(); + Arrays.sort(numbers); + for (int k = numbers.length-1; k >= 0; k--) { + int num_k = numbers[k]; + if(k+1 0){ + j--; + }else if(num_i + num_j + num_k < 0){ + i++; + }else{ + ArrayList solution = new ArrayList(); + solution.add(num_i); + solution.add(num_j); + solution.add(num_k); + solutions.add(solution); + while (i+1= 0; k--) { + int num_k = numbers[k]; + int target_k = target - num_k; + + int i = 0, j = k-1; + while (i < j) { + int num_i = numbers[i], num_j = numbers[j]; + int diff = Math.abs(num_i+num_j+num_k-target); + if (diff < min) { + min = diff; + sum = num_i+num_j+num_k; + } + if (num_i + num_j < target_k) { + i++; + }else if(num_i + num_j > target_k){ + j--; + + }else{ + return sum; + } + } + } + + return sum; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L1/TriangleCount.java b/Algorithm-Java/src/Lintcode/Intensive/L1/TriangleCount.java new file mode 100644 index 0000000..f07bb5c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L1/TriangleCount.java @@ -0,0 +1,31 @@ +package Lintcode.Intensive.L1; + +public class TriangleCount { + /* + * triangle count + */ + public int triangleCount(int S[]) { + int cnt = 0; + + for (int k = S.length-1; k >= 0; k--) { + int i = 0, j = k-1; + while (i < j) { + int num_i = S[i], num_j = S[j]; + if (num_i + num_j > S[k]) { + cnt += j-i; + --j; + }else{ + i++; + } + } + } + + return cnt; + } + + public static void main(String[] args) { + int[] S = {4,4,4,4}; + int cnt = new TriangleCount().triangleCount(S); + System.out.println(cnt); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L1/TwoSum.java b/Algorithm-Java/src/Lintcode/Intensive/L1/TwoSum.java new file mode 100644 index 0000000..5858b36 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L1/TwoSum.java @@ -0,0 +1,139 @@ +package Lintcode.Intensive.L1; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; + +public class TwoSum { + /* + * @param numbers : An array of Integer + * @param target : target = numbers[index1] + numbers[index2] + * @return : [index1 + 1, index2 + 1] (index1 < index2) + */ + public int[] twoSum(int[] numbers, int target) { + HashMap num2idx = new HashMap<>(); + for (int i = 0; i < numbers.length; i++) { + int num = numbers[i]; + if (num2idx.containsKey(target - num)) { + int[] result = new int[2]; + result[1] = i+1; + result[0] = num2idx.get(target - num); + return result; + } + num2idx.put(num, i+1); + } + + return null; + } + + /* + * The index solution + */ + class Num{ + int num; + int idx; + + public Num(int num, int idx) { + this.num = num; + this.idx = idx; + } + } + + public int[] twoSum2(int[] numbers, int target) { + ArrayList nums = new ArrayList<>(); + for (int i = 0; i < numbers.length; i++) { + Num num = new Num(numbers[i], i+1); + nums.add(num); + } + Collections.sort(nums, new Comparator() { + @Override + public int compare(Num o1, Num o2) { + return o1.num - o2.num; + } + }); + int i = 0, j = numbers.length - 1; + while (i < j) { + Num num_i = nums.get(i), num_j = nums.get(j); + if (num_i.num+num_j.num < target) { + ++i; + }else if(num_i.num+num_j.num > target){ + --j; + }else{ + int[] result = new int[2]; + result[0] = num_i.idx < num_j.idx?num_i.idx:num_j.idx; + result[1] = num_i.idx > num_j.idx?num_i.idx:num_j.idx; + return result; + } + } + return null; + } + + /* + * two sum extension larger + */ + public int[] twoSumLarger(int[] numbers, int target) { + ArrayList nums = new ArrayList<>(); + for (int i = 0; i < numbers.length; i++) { + Num num = new Num(numbers[i], i+1); + nums.add(num); + } + Collections.sort(nums, new Comparator() { + @Override + public int compare(Num o1, Num o2) { + return o1.num - o2.num; + } + }); + + int i = 0, j = numbers.length - 1; + while (i < j) { + Num num_i = nums.get(i), num_j = nums.get(j); + if (num_i.num+num_j.num <= target) { + ++i; + }else{ + int[] result = new int[2]; + result[0] = num_i.idx < num_j.idx?num_i.idx:num_j.idx; + result[1] = num_i.idx > num_j.idx?num_i.idx:num_j.idx; + return result; + } + } + + return null; + } + + /* + * two sum extension larger count + */ + public int twoSumExCnt(int[] numbers, int target) { + Arrays.sort(numbers); + int cnt = 0; + int i = 0, j = numbers.length-1; + while (i < j) { + int num_i = numbers[i], num_j = numbers[j]; + if (num_i + num_j > target) { + cnt += j-i; + --j; + }else{ + i++; + } + } + return cnt; + } + + + + public static void main(String[] args) { + if(false){ + int[] numbers = {5,4,3,7,8}; + int[] solutions = new TwoSum().twoSumLarger(numbers, 14); + System.out.println(solutions[0] + "-" + solutions[1]); + }else if(false){ + int[] numbers = {5,4,3,7,8}; + int cnt = new TwoSum().twoSumExCnt(numbers, 8); + System.out.println(cnt); + } + + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L2/ConnectedSet.java b/Algorithm-Java/src/Lintcode/Intensive/L2/ConnectedSet.java new file mode 100644 index 0000000..17702ac --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L2/ConnectedSet.java @@ -0,0 +1,25 @@ +package Lintcode.Intensive.L2; + +import java.util.ArrayList; +import java.util.List; + +class UndirectedGraphNode { + int label; + ArrayList neighbors; + + UndirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } +}; + +public class ConnectedSet { + /** + * @param nodes + * a array of Undirected graph node + * @return a connected set of a Undirected graph + */ + public List> connectedSet(ArrayList nodes) { + return null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L2/CountOfAirplanes.java b/Algorithm-Java/src/Lintcode/Intensive/L2/CountOfAirplanes.java new file mode 100644 index 0000000..feaa1c0 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L2/CountOfAirplanes.java @@ -0,0 +1,85 @@ +package Lintcode.Intensive.L2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +class Interval { + int start, end; + + Interval(int start, int end) { + this.start = start; + this.end = end; + } +} + +class Entry { + public int point; + public boolean start; + + public Entry(int point, boolean start) { + this.point = point; + this.start = start; + } +} + +class ListComparator implements Comparator { + + @Override + public int compare(Entry o1, Entry o2) { + // TODO Auto-generated method stub + return o1.point - o2.point; + } + +} + +public class CountOfAirplanes { + /** + * @param intervals: + * An interval array + * @return: Count of airplanes are in the sky. + */ + public int countOfAirplanes(List airplanes) { + if (airplanes == null || airplanes.size() == 0) { + return 0; + } + + ArrayList list = new ArrayList<>(); + + for (int i = 0; i < airplanes.size(); i++) { + list.add(new Entry(airplanes.get(i).start, true)); + list.add(new Entry(airplanes.get(i).end, false)); + } + Collections.sort(list, new ListComparator()); + + int cnt = 0, max_value = Integer.MIN_VALUE; + + int i = 0; + while (true) { + + while (true) { + if (list.get(i).start) { + cnt++; + } else { + cnt--; + } + if (i + 1 < list.size() && list.get(i + 1).point == list.get(i).point) { + ++i; + continue; + }else{ + break; + } + } + if (cnt > max_value) { + max_value = cnt; + } + i++; + if (i == list.size()) { + break; + } + } + + return max_value; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L2/Insert.java b/Algorithm-Java/src/Lintcode/Intensive/L2/Insert.java new file mode 100644 index 0000000..5a5fcba --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L2/Insert.java @@ -0,0 +1,60 @@ +package Lintcode.Intensive.L2; + +import java.util.ArrayList; +import java.util.Collections; + + +public class Insert { + /** + * Insert newInterval into intervals. + * + * @param intervals: + * Sorted interval list. + * @param newInterval: + * A new interval. + * @return: A new sorted interval list. + */ + public ArrayList insert(ArrayList intervals, Interval newInterval) { + ArrayList result = new ArrayList(); + + ArrayList entries = new ArrayList(); + for (int i = 0; i < intervals.size(); i++) { + entries.add(new Entry(intervals.get(i).start, true)); + entries.add(new Entry(intervals.get(i).end, false)); + } + entries.add(new Entry(newInterval.start, true)); + entries.add(new Entry(newInterval.end, false)); + Collections.sort(entries, new EntryComparator()); + + int i = 0, cnt = 0, start = -1, end =-1; + while (true) { + while (true) { + if(entries.get(i).start){ + if (start == -1) { + start = entries.get(i).point; + } + ++cnt; + }else{ + --cnt; + } + if (i+1{ + + @Override + public int compare(Entry o1, Entry o2) { + // TODO Auto-generated method stub + return o1.point - o2.point; + } + +} + +public class Merge { + /** + * @param intervals, + * a collection of intervals + * @return: A new sorted interval list. + */ + public List merge(List intervals) { + if(intervals == null || intervals.size() == 0){ + return new ArrayList(); + } + ArrayList entries = new ArrayList(); + for (int i = 0; i < intervals.size(); i++) { + Interval interval = intervals.get(i); + entries.add(new Entry(interval.start, true)); + entries.add(new Entry(interval.end, false)); + } + Collections.sort(entries, new EntryComparator()); + + ArrayList solutions = new ArrayList(); + int count = 0, s = -1, e = -1; + int i = 0; + while (true) { + + while (true) { + if (entries.get(i).start) { + if (s == -1) { + s = entries.get(i).point; + } + ++count; + }else{ + --count; + } + if (i+1= 0 && grid[i - 1][j] && uFind.compressed_find((i - 1) * grid[0].length + j) != uFind + .compressed_find(i * grid[0].length + j)) { + uFind.compressed_merge((i - 1) * grid[0].length + j, i * grid[0].length + j); + --cnt; + } + if (j - 1 >= 0 && grid[i][j - 1] && uFind.compressed_find(i * grid[0].length + j - 1) != uFind + .compressed_find(i * grid[0].length + j)) { + uFind.compressed_merge(i * grid[0].length + j - 1, i * grid[0].length + j); + --cnt; + } + } + } + } + + return cnt; + } + + public List numIslands2(int m, int n, int[][] positions) { + ArrayList solutions = new ArrayList<>(); + int cnt = 0; + UnionFind uFind = new UnionFind(m * n); + + boolean[] seas = new boolean[m * n]; + + for (int k = 0; k < positions.length; k++) { + ++cnt; + + int[] position = positions[k]; + int index = position[0] * n + position[1]; + seas[index] = true; + + if (position[0] - 1 >= 0 && seas[(position[0] - 1) * n + position[1]] + && uFind.compressed_find((position[0] - 1) * n + position[1]) != uFind.compressed_find(index)) { + uFind.compressed_merge(index, (position[0] - 1) * n + position[1]); + --cnt; + } + if (position[1] - 1 >= 0 && seas[(position[0]) * n + position[1] - 1] + && uFind.compressed_find((position[0]) * n + position[1] - 1) != uFind.compressed_find(index)) { + uFind.compressed_merge(index, (position[0]) * n + position[1] - 1); + --cnt; + } + if (position[0] + 1 < m && seas[(position[0] + 1) * n + position[1]] + && uFind.compressed_find((position[0] + 1) * n + position[1]) != uFind.compressed_find(index)) { + uFind.compressed_merge(index, (position[0] + 1) * n + position[1]); + --cnt; + } + if (position[1] + 1 < n && seas[(position[0]) * n + position[1] + 1] + && uFind.compressed_find((position[0]) * n + position[1] + 1) != uFind.compressed_find(index)) { + uFind.compressed_merge(index, (position[0]) * n + position[1] + 1); + --cnt; + } + + solutions.add(cnt); + } + + return solutions; + } + + public static void main(String[] args) { + int[][] positions = {{0,0},{0,1},{1,2},{2,1}}; + List solutions = new NumIslands().numIslands2(3, 3, positions); + for (Integer cnt : solutions) { + System.out.println(cnt); + } + + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L2/SurroundedRegions.java b/Algorithm-Java/src/Lintcode/Intensive/L2/SurroundedRegions.java new file mode 100644 index 0000000..e04cb67 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L2/SurroundedRegions.java @@ -0,0 +1,71 @@ +package Lintcode.Intensive.L2; + +import java.util.LinkedList; +import java.util.Queue; + +public class SurroundedRegions { + /** + * @param board + * a 2D board containing 'X' and 'O' + * @return void + */ + public void surroundedRegions(char[][] board) { + if(board == null || board.length ==0 || board[0].length == 0){ + return; + } + int m = board.length, n = board[0].length; + boolean[] checked = new boolean[m * n]; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (i == 0 || j == 0 || i == m - 1 || j == n-1) { + if (board[i][j] == 'O') { + board[i][j] = 'M'; + // bfs + Queue queue = new LinkedList<>(); + queue.add(i * n + j); + while (!queue.isEmpty()) { + int pos = queue.poll(); + int x = pos / n, y = pos % n; + if (x - 1 >= 0 && !checked[(x - 1) * n + y] && board[x - 1][y] == 'O') { + board[x - 1][y] = 'M'; + checked[(x - 1) * n + y] = true; + queue.add((x - 1) * n + y); + } + if (y - 1 >= 0 && !checked[(x) * n + y - 1] && board[x][y - 1] == 'O') { + board[x][y - 1] = 'M'; + checked[(x) * n + y - 1] = true; + queue.add((x) * n + y - 1); + } + if (x + 1 < m && !checked[(x + 1) * n + y] && board[x + 1][y] == 'O') { + board[x + 1][y] = 'M'; + checked[(x + 1) * n + y] = true; + queue.add((x + 1) * n + y); + } + if (y + 1 < n && !checked[(x) * n + y + 1] && board[x][y + 1] == 'O') { + board[x][y + 1] = 'M'; + checked[(x) * n + y + 1] = true; + queue.add((x) * n + y + 1); + } + } + } + } + } + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if(board[i][j] == 'O'){ + board[i][j] = 'X'; + } + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if(board[i][j] == 'M'){ + board[i][j] = 'O'; + } + } + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L2/ValidTree.java b/Algorithm-Java/src/Lintcode/Intensive/L2/ValidTree.java new file mode 100644 index 0000000..1f0e9f9 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L2/ValidTree.java @@ -0,0 +1,40 @@ +package Lintcode.Intensive.L2; + +import Lintcode.Util.UnionFind; + +public class ValidTree { + /** + * @param n + * an integer + * @param edges + * a list of undirected edges + * @return true if it's a valid tree, or false + */ + public boolean validTree(int n, int[][] edges) { + if (edges == null || edges.length == 0) { + if (n == 1) { + return true; + } else { + return false; + } + } + UnionFind uFind = new UnionFind(n); + for (int i = 0; i < edges.length; i++) { + int[] pos = edges[i]; + int s = pos[0], e = pos[1]; + + if (uFind.compressed_find(s) == uFind.compressed_find(e)) { + return false; + } + uFind.compressed_merge(s, e); + + } + int mark = uFind.compressed_find(0); + for (int i = 1; i < n; i++) { + if (uFind.compressed_find(i) != mark) { + return false; + } + } + return true; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L2/WordDictionary.java b/Algorithm-Java/src/Lintcode/Intensive/L2/WordDictionary.java new file mode 100644 index 0000000..9b211e6 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L2/WordDictionary.java @@ -0,0 +1,67 @@ +package Lintcode.Intensive.L2; + +import java.util.ArrayList; + +import Lintcode.Util.Trie; + +public class WordDictionary { + + Trie root ; + + public WordDictionary() { + this.root = new Trie(); + } + + // Adds a word into the data structure. + public void addWord(String word) { + Trie temp = root; + for (int i = 0; i < word.length(); i++) { + char ch = word.charAt(i); + if (!temp.children.containsKey(ch)) { + temp.children.put(ch, new Trie()); + } + temp = temp.children.get(ch); + } + temp.marked = true; + } + + // Returns if the word is in the data structure. A word could + // contain the dot character '.' to represent any one letter. + public boolean search(String word) { + ArrayList temp = new ArrayList(); + temp.add(root); + for (int i = 0; i < word.length(); i++) { + char ch = word.charAt(i); + + ArrayList next_temp = new ArrayList(); + if (ch == '.') { + for (Trie trie : temp) { + for (char next_ch : trie.children.keySet()) { + next_temp.add(trie.children.get(next_ch)); + } + } + }else{ + for (Trie trie : temp) { + if (trie.children.containsKey(ch)) { + next_temp.add(trie.children.get(ch)); + } + } + } + temp = next_temp; + if (temp.isEmpty()) { + return false; + } + } + for (Trie trie : temp) { + if (trie.marked) { + return true; + } + } + return false; + } +} + +// Your WordDictionary object will be instantiated and called as such: +// WordDictionary wordDictionary = new WordDictionary(); +// wordDictionary.addWord("word"); +// wordDictionary.search("pattern"); \ No newline at end of file diff --git a/Algorithm-Java/src/Lintcode/Intensive/L3/BuildingOutline.java b/Algorithm-Java/src/Lintcode/Intensive/L3/BuildingOutline.java new file mode 100644 index 0000000..12cea9e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L3/BuildingOutline.java @@ -0,0 +1,92 @@ +package Lintcode.Intensive.L3; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import Lintcode.Util.HashHeap; + +//todo: not finished +public class BuildingOutline { + class BuildEntry { + public int index, height; + boolean start; + + public BuildEntry(int index, boolean start, int height) { + this.index = index; + this.height = height; + this.start = start; + } + } + + class BuildComparator implements Comparator { + + @Override + public int compare(BuildEntry o1, BuildEntry o2) { + return o1.index - o2.index; + } + + } + + /** + * @param buildings: + * A list of lists of integers + * @return: Find the outline of those buildings + */ + public ArrayList> buildingOutline(int[][] buildings) { + ArrayList> results = new ArrayList<>(); + if (buildings == null || buildings.length == 0 || buildings[0].length == 0) { + return results; + } + + ArrayList entries = new ArrayList<>(); + for (int i = 0; i < buildings.length; i++) { + entries.add(new BuildEntry(buildings[i][0], true, buildings[i][2])); + entries.add(new BuildEntry(buildings[i][1], false, buildings[i][2])); + } + Collections.sort(entries, new BuildComparator()); + + HashHeap heap = new HashHeap(true); + BuildEntry pre_entry = null; + for (int i = 0; i < entries.size(); i++) { + if (heap.getSize() == 0) { + pre_entry = entries.get(i); + } else { + if (entries.get(i).height > heap.peek()) { + ArrayList temp = new ArrayList<>(); + temp.add(pre_entry.index); + temp.add(entries.get(i).index); + temp.add(heap.peek()); + results.add(temp); + pre_entry = entries.get(i); + } + } + if (entries.get(i).start) { + heap.push(entries.get(i).height); + } else { + int temp_height = entries.get(i).height; + heap.delete(temp_height); + if (heap.getSize() == 0 || temp_height > heap.peek()) { + if(pre_entry.index < entries.get(i).index){ + ArrayList temp = new ArrayList<>(); + temp.add(pre_entry.index); + temp.add(entries.get(i).index); + temp.add(temp_height); + results.add(temp); + } + + if (temp_height > heap.peek()) { + pre_entry = entries.get(i); + } + } + + } + } + + return results; + } + + public static void main(String[] args) { + int[][] buildings = { { 1, 3, 3 }, { 2, 4, 4 }, { 5, 6, 1 } }; + new BuildingOutline().buildingOutline(buildings); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L3/MaxSlidingWindow.java b/Algorithm-Java/src/Lintcode/Intensive/L3/MaxSlidingWindow.java new file mode 100644 index 0000000..bfbe003 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L3/MaxSlidingWindow.java @@ -0,0 +1,44 @@ +package Lintcode.Intensive.L3; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.PriorityQueue; + +public class MaxSlidingWindow { + /** + * @param nums: + * A list of integers. + * @return: The maximum number inside the window at each moving. + */ + public ArrayList maxSlidingWindow(int[] nums, int k) { + ArrayList result = new ArrayList(nums.length - k + 1); + if (nums == null || nums.length == 0) { + return result; + }else if(nums.length == 1){ + result.add(nums[0]); + return result; + } + + + Deque deque = new ArrayDeque<>(); + deque.addLast(nums[0]); + for (int i = 1; i < nums.length; i++) { + while (deque.peekLast() < nums[i]) { + deque.removeLast(); + } + deque.addLast(nums[i]); + + if (i >= k -1) { + result.add(deque.peekLast()); + } + + if (deque.peekFirst() == nums[i - k]) { + deque.removeFirst(); + } + } + + return result; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L3/MedianII.java b/Algorithm-Java/src/Lintcode/Intensive/L3/MedianII.java new file mode 100644 index 0000000..c36fe31 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L3/MedianII.java @@ -0,0 +1,42 @@ +package Lintcode.Intensive.L3; + +import java.util.Collections; +import java.util.PriorityQueue; + +public class MedianII { + /** + * @param nums: + * A list of integers. + * @return: the median of numbers + */ + public int[] medianII(int[] nums) { + int[] results = new int[nums.length]; + + PriorityQueue smallerStack = new PriorityQueue(nums.length, Collections.reverseOrder()), largerStack = new PriorityQueue(); + + results[0] = nums[0]; + for (int i = 1; i < nums.length; i++) { + if (nums[i] >= results[i - 1]) { + largerStack.add(nums[i]); + } else { + smallerStack.add(nums[i]); + } + results[i] = results[i - 1]; + + // adjust + if (smallerStack.size() + 1 < largerStack.size()) { + while (smallerStack.size() + 1 < largerStack.size()) { + smallerStack.add(results[i]); + results[i] = largerStack.poll(); + } + } else if (smallerStack.size() - 1 >= largerStack.size()) { + while (smallerStack.size() + 1 > largerStack.size()) { + largerStack.add(results[i]); + results[i] = smallerStack.poll(); + } + } + } + + return results; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L3/MedianSlidingWindow.java b/Algorithm-Java/src/Lintcode/Intensive/L3/MedianSlidingWindow.java new file mode 100644 index 0000000..ca457fa --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L3/MedianSlidingWindow.java @@ -0,0 +1,51 @@ +package Lintcode.Intensive.L3; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.PriorityQueue; + +public class MedianSlidingWindow { + public ArrayList medianSlidingWindow(int[] nums, int k) { + ArrayList result = new ArrayList<>(); + + PriorityQueue minHeap = new PriorityQueue<>(k / 2, Collections.reverseOrder()); + PriorityQueue maxHeap = new PriorityQueue<>(k / 2); + + int median = nums[0]; + for (int i = 1; i < nums.length; i++) { + + if (i >= k) { + if (minHeap.contains(nums[i - k])) { + minHeap.remove(nums[i - k]); + } else if (maxHeap.contains(nums[i - k])) { + maxHeap.remove(nums[i - k]); + } + } + if (nums[i] >= median) { + maxHeap.offer(nums[i]); + } else { + minHeap.offer(nums[i]); + } + if (maxHeap.size() > 1 + minHeap.size()) { + minHeap.add(median); + median = maxHeap.poll(); + } else if (minHeap.size() > maxHeap.size()) { + maxHeap.add(median); + median = minHeap.poll(); + } + + if (i >= k - 1) { + result.add(median); + } + } + return result; + } + + public static void main(String[] args) { + int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + ArrayList result = new MedianSlidingWindow().medianSlidingWindow(nums, 3); + for (Integer median : result) { + System.out.println(median); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L3/TrapRainWater.java b/Algorithm-Java/src/Lintcode/Intensive/L3/TrapRainWater.java new file mode 100644 index 0000000..f6db9ed --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L3/TrapRainWater.java @@ -0,0 +1,125 @@ +package Lintcode.Intensive.L3; + +import java.util.Comparator; +import java.util.PriorityQueue; + +public class TrapRainWater { + /** + * @param heights: + * an array of integers + * @return: a integer + */ + public int trapRainWater(int[] heights) { + int sum = 0; + if (heights == null || heights.length == 0) { + return sum; + } + + int left = 0, right = heights.length - 1, previous_left_height = heights[left], + previous_right_height = heights[right]; + while (left < right) { + if (heights[left] < heights[right]) { + ++left; + if (heights[left] < previous_left_height) { + sum += previous_left_height - heights[left]; + } else { + previous_left_height = heights[left]; + } + } else { + --right; + if (heights[right] < previous_right_height) { + sum += previous_right_height - heights[right]; + } else { + previous_right_height = heights[right]; + } + } + + } + + return sum; + } + + class RectEntry { + public int x, y, val; + + public RectEntry(int x, int y, int val) { + this.x = x; + this.y = y; + this.val = val; + } + } + + class RectComparator implements Comparator { + + @Override + public int compare(RectEntry o1, RectEntry o2) { + return o1.val - o2.val; + } + + } + + public int trapRainWater(int[][] heightMap) { + if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) { + return 0; + } + + int sum = 0, m = heightMap.length, n = heightMap[0].length; + + boolean[][] visited = new boolean[m][n]; + PriorityQueue queue = new PriorityQueue(new RectComparator()); + + for (int i = 0; i < n; i++) { + queue.add(new RectEntry(0, i, heightMap[0][i])); + queue.add(new RectEntry(m - 1, i, heightMap[m - 1][i])); + visited[0][i] = true; + visited[m - 1][i] = true; + } + for (int i = 0; i < m; i++) { + queue.add(new RectEntry(i, 0, heightMap[i][0])); + queue.add(new RectEntry(i, n - 1, heightMap[i][n - 1])); + visited[i][0] = true; + visited[i][n - 1] = true; + } + + while (!queue.isEmpty()) { + RectEntry temp = queue.poll(); + if (temp.x - 1 >= 0 && !visited[temp.x - 1][temp.y]) { + if (heightMap[temp.x - 1][temp.y] < temp.val) { + sum += temp.val - heightMap[temp.x - 1][temp.y]; + } + queue.add(new RectEntry(temp.x - 1, temp.y, Math.max(heightMap[temp.x - 1][temp.y], temp.val))); + visited[temp.x - 1][temp.y] = true; + } + if (temp.x + 1 < m && !visited[temp.x + 1][temp.y]) { + if (heightMap[temp.x + 1][temp.y] < temp.val) { + sum += temp.val - heightMap[temp.x + 1][temp.y]; + } + queue.add(new RectEntry(temp.x + 1, temp.y, Math.max(heightMap[temp.x + 1][temp.y], temp.val))); + visited[temp.x + 1][temp.y] = true; + } + if (temp.y - 1 >= 0 && !visited[temp.x][temp.y - 1]) { + if (heightMap[temp.x][temp.y - 1] < temp.val) { + sum += temp.val - heightMap[temp.x][temp.y - 1]; + } + queue.add(new RectEntry(temp.x, temp.y - 1, Math.max(heightMap[temp.x][temp.y - 1], temp.val))); + visited[temp.x][temp.y - 1] = true; + } + if (temp.y + 1 < n && !visited[temp.x][temp.y + 1]) { + if (heightMap[temp.x][temp.y + 1] < temp.val) { + sum += temp.val - heightMap[temp.x][temp.y + 1]; + } + queue.add(new RectEntry(temp.x, temp.y + 1, Math.max(heightMap[temp.x][temp.y + 1], temp.val))); + visited[temp.x][temp.y + 1] = true; + } + + } + + return sum; + } + + public static void main(String[] args) { + int[][] heightMap = { { 1, 4, 3, 1, 3, 2 }, { 3, 2, 1, 3, 2, 4 }, { 2, 3, 3, 2, 3, 1 } }; + int sum = new TrapRainWater().trapRainWater(heightMap); + System.out.println(sum); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/HasCycle.java b/Algorithm-Java/src/Lintcode/Intensive/L4/HasCycle.java new file mode 100644 index 0000000..468e05b --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/HasCycle.java @@ -0,0 +1,73 @@ +package Lintcode.Intensive.L4; + +public class HasCycle { + + class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } + } + + public boolean hasCycle(ListNode head) { + if (head == null) { + return false; + } + + ListNode slow_node = head, fast_node = head; + while (true) { + slow_node = slow_node.next; + if (slow_node == null) { + return false; + } + fast_node = fast_node.next; + if (fast_node == null) { + return false; + } + fast_node = fast_node.next; + if (fast_node == null) { + return false; + } + + if (slow_node == fast_node) { + return true; + } + } + } + + public ListNode detectCycle(ListNode head) { + if (head == null) { + return null; + } + + ListNode slow_node = head, fast_node = head; + while (true) { + slow_node = slow_node.next; + if (slow_node == null) { + return null; + } + fast_node = fast_node.next; + if (fast_node == null) { + return null; + } + fast_node = fast_node.next; + if (fast_node == null) { + return null; + } + + if (slow_node == fast_node) { + break; + } + } + + while (head == slow_node.next) { + head = head.next; + slow_node = slow_node.next; + } + + return head; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/KthLargestElement.java b/Algorithm-Java/src/Lintcode/Intensive/L4/KthLargestElement.java new file mode 100644 index 0000000..63b76e5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/KthLargestElement.java @@ -0,0 +1,52 @@ +package Lintcode.Intensive.L4; + +import com.sun.org.apache.bcel.internal.generic.NEW; + +public class KthLargestElement { + /* + * @param k : description of k + * + * @param nums : array of nums + * + * @return: description of return + */ + public int kthLargestElement(int k, int[] nums) { + if (nums == null || nums.length == 0) { + return -1; + } + + int pivot, start = 0, end = nums.length - 1, pre_start = 0, pre_end = nums.length - 1; + + while (true) { + pivot = nums[start]; + pre_start = start; + pre_end = end; + while (start < end) { + for (; start < end && nums[end] <= pivot;) + --end; + nums[start] = nums[end]; + + for (; start < end && nums[start] >= pivot;) + ++start; + nums[end] = nums[start]; + } + nums[start] = pivot; + + if (start == k - 1) { + return nums[start]; + }else if(start < k - 1){ + start = start + 1; + end = pre_end; + }else{ + end = start - 1; + start = pre_start; + } + } + + } + + public static void main(String[] args) { + int[] nums = {9,3,2,4,8}; + System.out.println(new KthLargestElement().kthLargestElement(3, nums)); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/LengthOfLongestSubstring.java b/Algorithm-Java/src/Lintcode/Intensive/L4/LengthOfLongestSubstring.java new file mode 100644 index 0000000..8e53b69 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/LengthOfLongestSubstring.java @@ -0,0 +1,34 @@ +package Lintcode.Intensive.L4; + +import java.util.HashMap; +import java.util.HashSet; + +public class LengthOfLongestSubstring { + /** + * @param s: + * a string + * @return: an integer + */ + public int lengthOfLongestSubstring(String s) { + int longest_length = 0; + if (s == null || s.length() == 0) { + return longest_length; + } + + boolean[] checker = new boolean[0XFF]; + int left = 0, right = 0; + for (left = 0; left < s.length(); left++) { + while (right < s.length() && !checker[s.charAt(right)]) { + char ch_right = s.charAt(right); + ++right; + checker[ch_right] = true; + if (right - left > longest_length) { + longest_length = right - left; + } + } + checker[s.charAt(left)] = false; + } + + return longest_length; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/LengthOfLongestSubstringTwoDistinct.java b/Algorithm-Java/src/Lintcode/Intensive/L4/LengthOfLongestSubstringTwoDistinct.java new file mode 100644 index 0000000..9f32375 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/LengthOfLongestSubstringTwoDistinct.java @@ -0,0 +1,41 @@ +package Lintcode.Intensive.L4; + +import java.util.HashMap; + +public class LengthOfLongestSubstringTwoDistinct { + public int lengthOfLongestSubstringTwoDistinct(String s) { + if (s == null || s.length() == 0) { + return 0; + } + + HashMap checker = new HashMap<>(); + int left = 0, right = 0, longest_substr = 0, distinct_char = 0; + for (left = 0; left < s.length(); left++) { + while (right < s.length() && distinct_char <= 2) { + char ch_right = s.charAt(right); + if (!checker.containsKey(ch_right)) { + checker.put(ch_right, 0); + distinct_char++; + } + checker.put(ch_right, 1 + checker.get(ch_right)); + + ++right; + if (distinct_char == 2 && right - left > longest_substr) { + longest_substr = right - left; + } + } + + char ch_left = s.charAt(left); + checker.put(ch_left, checker.get(ch_left) - 1); + if (checker.get(ch_left) == 0) { + distinct_char--; + } + } + return longest_substr; + } + + public static void main(String[] args) { + int longest = new LengthOfLongestSubstringTwoDistinct().lengthOfLongestSubstringTwoDistinct("abac"); + System.out.println(longest); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/MergeTwoLists.java b/Algorithm-Java/src/Lintcode/Intensive/L4/MergeTwoLists.java new file mode 100644 index 0000000..c2280ce --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/MergeTwoLists.java @@ -0,0 +1,48 @@ +package Lintcode.Intensive.L4; + +public class MergeTwoLists { + class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } + } + + /** + * @param ListNode + * l1 is the head of the linked list + * @param ListNode + * l2 is the head of the linked list + * @return: ListNode head of linked list + */ + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode head = new ListNode(0); + ListNode last = head; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + last.next = l1; + last = l1; + l1 = l1.next; + } else { + last.next = l2; + last = l2; + l2 = l2.next; + } + } + while (l1 != null) { + last.next = l1; + last = l1; + l1 = l1.next; + } + while (l2 != null) { + last.next = l2; + last = l2; + l2 = l2.next; + } + + return head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/MiddleNode.java b/Algorithm-Java/src/Lintcode/Intensive/L4/MiddleNode.java new file mode 100644 index 0000000..a742b3f --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/MiddleNode.java @@ -0,0 +1,17 @@ +package Lintcode.Intensive.L4; + +public class MiddleNode { + class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } + } + + public ListNode middleNode(ListNode head) { + return null; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/MinWindow.java b/Algorithm-Java/src/Lintcode/Intensive/L4/MinWindow.java new file mode 100644 index 0000000..02c4d68 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/MinWindow.java @@ -0,0 +1,68 @@ +package Lintcode.Intensive.L4; + +import java.util.HashMap; +import java.util.HashSet; + +public class MinWindow { + /** + * @param source: + * A string + * @param target: + * A string + * @return: A string denote the minimum window Return "" if there is no such + * a string + */ + public String minWindow(String source, String target) { + if (source == null || source.length() == 0 || target == null || target.length() == 0) { + return ""; + } + int[] checker = new int[0XFF], origin = new int[0XFF]; + HashSet chars = new HashSet<>(); + HashSet chars_issue = new HashSet<>(); + for (int i = 0; i < target.length(); i++) { + char ch = target.charAt(i); + checker[ch]++; + chars.add(ch); + chars_issue.add(ch); + } + + int left = 0, right = 0, max_left = 0, max_right = Integer.MAX_VALUE; + for (left = 0; left < source.length(); left++) { + while (right < source.length() && chars_issue.size() > 0) { + char ch_right = source.charAt(right); + if (chars.contains(ch_right)) { + checker[ch_right]--; + } + if (checker[ch_right] == 0) { + chars_issue.remove(ch_right); + } + if (chars_issue.isEmpty() && right - left < max_right - max_left) { + max_left = left; + max_right = right; + } + ++right; + } + if (chars_issue.isEmpty() && right - 1 - left < max_right - max_left) { + max_left = left; + max_right = right - 1; + } + char ch_left = source.charAt(left); + if (chars.contains(ch_left)) { + checker[ch_left]++; + if (checker[ch_left] > 0) { + chars_issue.add(ch_left); + } + } + } + if (max_right == Integer.MAX_VALUE) { + return ""; + } + + return source.substring(max_left, max_right + 1); + } + + public static void main(String[] args) { + String win = new MinWindow().minWindow("adfqeradboaf23098724huhfda923hadf78adfhadfhadfaodiyfas8", "dfje89affefy8f"); + System.out.println(win); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/MinimumSize.java b/Algorithm-Java/src/Lintcode/Intensive/L4/MinimumSize.java new file mode 100644 index 0000000..ded03d9 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/MinimumSize.java @@ -0,0 +1,41 @@ +package Lintcode.Intensive.L4; + +import java.util.Arrays; + +public class MinimumSize { + /** + * @param nums: + * an array of integers + * @param s: + * an integer + * @return: an integer representing the minimum size of subarray + */ + public int minimumSize(int[] nums, int s) { + if (nums == null || nums.length == 0) { + return -1; + } + + int left = 0, right = 0, window_sum = 0, min_cnt = Integer.MAX_VALUE; + + for (left = 0; left < nums.length; left++) { + while (right < nums.length && window_sum < s) { + window_sum += nums[right]; + ++right; + } + if (window_sum >= s) { + if (min_cnt > right - left) { + min_cnt = right - left; + } + window_sum -= nums[left]; + } + } + + return min_cnt == Integer.MAX_VALUE ? -1 : min_cnt; + } + + public static void main(String[] args) { + int[] nums = { 2, 3, 1, 2 }; + int min_cnt = new MinimumSize().minimumSize(nums, 7); + System.out.println(min_cnt); + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/RemoveNthFromEnd.java b/Algorithm-Java/src/Lintcode/Intensive/L4/RemoveNthFromEnd.java new file mode 100644 index 0000000..846959d --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/RemoveNthFromEnd.java @@ -0,0 +1,46 @@ +package Lintcode.Intensive.L4; + +class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} + +public class RemoveNthFromEnd { + /** + * @param head: + * The first node of linked list. + * @param n: + * An integer. + * @return: The head of linked list. + */ + ListNode removeNthFromEnd(ListNode head, int n) { + if (head == null || n == 0) { + return null; + } + ListNode pre_head = new ListNode(0); + pre_head.next = head; + + ListNode loop_slow = pre_head, loop_fast = pre_head; + for (int i = 0; i <= n - 1; i++) { + loop_fast = loop_fast.next; + if (loop_fast.next == null) { + return null; + } + } + while (true) { + if (loop_fast.next == null) { + break; + } + loop_slow = loop_slow.next; + loop_fast = loop_fast.next; + } + loop_slow.next = loop_slow.next.next; + + return pre_head.next; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/SmallestDifference.java b/Algorithm-Java/src/Lintcode/Intensive/L4/SmallestDifference.java new file mode 100644 index 0000000..4b27892 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/SmallestDifference.java @@ -0,0 +1,34 @@ +package Lintcode.Intensive.L4; + +import java.util.Arrays; + +public class SmallestDifference { + /** + * @param A, + * B: Two integer arrays. + * @return: Their smallest difference. + */ + public int smallestDifference(int[] A, int[] B) { + int smallest = Integer.MAX_VALUE; + + Arrays.sort(A); + Arrays.sort(B); + + int i = 0, j = 0; + while (i < A.length && j < B.length) { + if (A[i] <= B[j]) { + smallest = Math.min(smallest, Math.abs(A[i] - B[j])); + if (i < A.length) { + ++i; + } + } else if (A[i] > B[j]) { + smallest = Math.min(smallest, Math.abs(A[i] - B[j])); + if (j < B.length) { + ++j; + } + } + } + + return smallest; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L4/SortNutsAndBolts.java b/Algorithm-Java/src/Lintcode/Intensive/L4/SortNutsAndBolts.java new file mode 100644 index 0000000..d4ddb10 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L4/SortNutsAndBolts.java @@ -0,0 +1,70 @@ +package Lintcode.Intensive.L4; + +import java.util.Iterator; + +class NBComparator { + public int cmp(String a, String b) { + return -1; + } +} + +public class SortNutsAndBolts { + + /** + * @param nuts: + * an array of integers + * @param bolts: + * an array of integers + * @param compare: + * a instance of Comparator + * @return: nothing + */ + public void sortNutsAndBolts(String[] nuts, String[] bolts, NBComparator compare) { + if (nuts == null || bolts == null || nuts.length == 0 || bolts.length == 0 || nuts.length != bolts.length) { + return; + } + qsort(nuts, bolts, compare, 0, nuts.length - 1); + } + + void qsort(String[] nuts, String[] bolts, NBComparator compare, int start, int end) { + while (start < end) { + int pivot_idx = partition(nuts, bolts[start], start, end, compare); + partition(bolts, nuts[pivot_idx], start, end, compare); + + qsort(nuts, bolts, compare, start, pivot_idx - 1); + qsort(nuts, bolts, compare, pivot_idx + 1, end); + } + } + + int partition(String[] target_array, String pivot, int start, int end, NBComparator compare) { + for (int i = start; i <= end; i++) { + if (compare.cmp(pivot, target_array[i]) == 0 || compare.cmp(target_array[i], pivot) == 0) { + swap(target_array, i, start); + break; + } + } + + String target_pivot = target_array[start]; + while (start < end) { + while (start < end + && (compare.cmp(target_array[end], pivot) == -1 || compare.cmp(pivot, target_array[end]) == 1)) { + --end; + } + target_array[start] = target_array[end]; + + while (start < end && (compare.cmp(target_array[start], pivot) == 1 + || compare.cmp(pivot, target_array[start]) == -1)) { + ++start; + } + target_array[end] = target_array[start]; + } + target_array[start] = target_pivot; + return start; + } + + void swap(String[] target_array, int i, int j) { + String temp = target_array[i]; + target_array[i] = target_array[j]; + target_array[j] = temp; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L5/MaxProduct.java b/Algorithm-Java/src/Lintcode/Intensive/L5/MaxProduct.java new file mode 100644 index 0000000..928818a --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L5/MaxProduct.java @@ -0,0 +1,30 @@ +package Lintcode.Intensive.L5; + +public class MaxProduct { + /** + * @param nums: + * an array of integers + * @return: an integer + */ + public int maxProduct(int[] nums) { + int pre_current_max = Math.max(1, nums[0]), max = nums[0], current_max = 0; + int pre_current_min = Math.min(1, nums[0]), min = nums[0], current_min = 0; + + for (int i = 1; i < nums.length; i++) { + + if (nums[i] > 0) { + current_max = Math.max(nums[i], pre_current_max * nums[i]); + current_min = Math.min(nums[i], pre_current_min * nums[i]); + } else if (nums[i] < 0) { + current_max = Math.max(nums[i], pre_current_min * nums[i]); + current_min = Math.min(nums[i], pre_current_max * nums[i]); + } + max = Math.max(max, current_max); + min = Math.min(min, current_min); + pre_current_min = current_min; + pre_current_max = current_max; + } + + return max; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L5/MaxProfit.java b/Algorithm-Java/src/Lintcode/Intensive/L5/MaxProfit.java new file mode 100644 index 0000000..9cb460e --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L5/MaxProfit.java @@ -0,0 +1,87 @@ +package Lintcode.Intensive.L5; + +public class MaxProfit { + /** + * @param prices: + * Given an integer array + * @return: Maximum profit + */ + public int maxProfit(int[] prices) { + int max_profit = 0; + if (prices == null || prices.length <= 1) { + return max_profit; + } + + int min_invest = prices[0]; + for (int i = 1; i < prices.length; i++) { + max_profit = Math.max(max_profit, prices[i] - min_invest); + min_invest = Math.min(min_invest, prices[i]); + } + + return max_profit; + } + + /** + * @param prices: + * Given an integer array + * @return: Maximum profit + */ + public int maxProfit2(int[] prices) { + int profit = 0; + if (prices == null || prices.length == 0) { + return profit; + } + + for (int i = 1; i < prices.length; i++) { + if (prices[i] > prices[i - 1]) { + profit += prices[i] - prices[i - 1]; + } + } + + return profit; + } + + /** + * @param prices: + * Given an integer array + * @return: Maximum profit + */ + public int maxProfit3(int[] prices) { + if (prices == null || prices.length <= 1) { + return 0; + } + int min_invest = prices[0]; + int[] left_profit = new int[prices.length]; + left_profit[0] = 0; + for (int i = 1; i < prices.length; i++) { + min_invest = Math.min(min_invest, prices[i]); + left_profit[i] = Math.max(left_profit[i - 1], prices[i] - min_invest); + } + + int max_sold = prices[prices.length - 1]; + int[] right_profit = new int[prices.length]; + right_profit[prices.length - 1] = 0; + for (int i = prices.length - 2; i >= 0; i--) { + max_sold = Math.max(max_sold, prices[i]); + right_profit[i] = Math.max(right_profit[i + 1], max_sold - prices[i]); + } + + int max_profit = 0; + for (int i = 0; i < prices.length - 1; i++) { + max_profit = Math.max(max_profit, left_profit[i] + right_profit[i]); + } + + return max_profit; + } + + /** + * @param k: + * An integer + * @param prices: + * Given an integer array + * @return: Maximum profit + */ + public int maxProfit4(int k, int[] prices) { + return -1; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L5/MaxTwoSubArrays.java b/Algorithm-Java/src/Lintcode/Intensive/L5/MaxTwoSubArrays.java new file mode 100644 index 0000000..6650573 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L5/MaxTwoSubArrays.java @@ -0,0 +1,80 @@ +package Lintcode.Intensive.L5; + +import java.util.ArrayList; + +public class MaxTwoSubArrays { + /** + * @param nums: + * A list of integers + * @return: A integer indicate the sum of max subarray + */ + public int maxSubArray(int[] nums) { + int current_max = Math.max(0, nums[0]), max = nums[0]; + + for (int i = 1; i < nums.length; i++) { + current_max = Math.max(nums[i], nums[i] + current_max); + max = Math.max(max, current_max); + } + + return max; + } + + /** + * @param nums: + * A list of integers + * @return: An integer denotes the sum of max two non-overlapping subarrays + */ + public int maxTwoSubArrays(ArrayList nums) { + int[] left_current_max = new int[nums.size()], left_max = new int[nums.size()]; + left_max[0] = nums.get(0); + left_current_max[0] = nums.get(0); + for (int i = 1; i < nums.size(); i++) { + left_current_max[i] = Math.max(nums.get(i), left_current_max[i - 1] + nums.get(i)); + left_max[i] = Math.max(left_max[i - 1], left_current_max[i]); + } + + int[] right_current_max = new int[nums.size()], right_max = new int[nums.size()]; + right_current_max[nums.size() - 1] = nums.get(nums.size() - 1); + right_max[nums.size() - 1] = nums.get(nums.size() - 1); + for (int i = nums.size() - 2; i >= 0; i--) { + right_current_max[i] = Math.max(nums.get(i), right_current_max[i + 1] + nums.get(i)); + right_max[i] = Math.max(right_max[i + 1], right_current_max[i]); + } + + int max_value = Integer.MIN_VALUE; + for (int i = 0; i < nums.size() - 1; i++) { + max_value = Math.max(left_max[i] + right_max[i + 1], max_value); + } + + return max_value; + } + + /** + * @param nums: + * A list of integers + * @param k: + * An integer denote to find k non-overlapping subarrays + * @return: An integer denote the sum of max k non-overlapping subarrays + */ + public int maxSubArray(int[] nums, int k) { + + //todo not finished backpack + int len = nums.length; + int[][] current_max = new int[len][len]; + int[][] global_max = new int[len][len]; + + for (int i = 0; i < len; i++) { + current_max[i][0] = nums[i]; + global_max[i][0] = nums[i]; + for (int j = i + 1; j < len; j++) { + current_max[i][j] = Math.max(current_max[i][j - 1], current_max[i][j - 1] + nums[j]); + global_max[i][j] = Math.max(current_max[i][j], global_max[i][j - 1]); + } + } + + int max_value = Integer.MIN_VALUE; + + + return max_value; + } +} diff --git a/Algorithm-Java/src/Lintcode/Intensive/L6/FirstWillWin.java b/Algorithm-Java/src/Lintcode/Intensive/L6/FirstWillWin.java new file mode 100644 index 0000000..b91fc08 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Intensive/L6/FirstWillWin.java @@ -0,0 +1,71 @@ +package Lintcode.Intensive.L6; + +public class FirstWillWin { + /** + * @param n: + * an integer + * @return: a boolean which equals to true if the first player will win + */ + public boolean firstWillWin(int n) { + boolean[] dp = new boolean[1 + n]; + boolean[] flag = new boolean[1 + n]; + return searchMemory(n, dp, flag); + } + + boolean searchMemory(int n, boolean[] dp, boolean[] flag) { + if (flag[n]) { + return dp[n]; + } + if (n == 0) { + dp[n] = false; + } else if (n == 1 || n == 2) { + dp[n] = true; + } else { + // dp[n] = !searchMemory(n - 1, dp, flag) || !searchMemory(n - 2, + // dp, flag); + dp[n] = (searchMemory(n - 2, dp, flag) && searchMemory(n - 3, dp, flag)) + || (searchMemory(n - 3, dp, flag) && searchMemory(n - 4, dp, flag)); + } + flag[n] = true; + return dp[n]; + } + + /** + * @param values: + * an array of integers + * @return: a boolean which equals to true if the first player will win + */ + public boolean firstWillWin2(int[] values) { + int target = 0; + for (int i = 0; i < values.length; i++) { + target += values[i]; + } + target = (target + 1) / 2; + + int[] dp = new int[values.length + 1]; + boolean[] flag = new boolean[values.length + 1]; + + return searchMemory(0, values, dp, flag) > target; + } + + int searchMemory(int idx, int[] values, int[] dp, boolean[] flag) { + if (flag[idx]) { + return dp[idx]; + } + if (idx == 0) { + dp[idx] = values[idx]; + } else if (idx == 1) { + dp[idx] = values[idx] + values[idx + 1]; + } else if (idx == 2) { + dp[idx] = values[idx + 1] + values[idx + 2]; + } else { + dp[idx] = Math.max( + (Math.min(searchMemory(idx - 2, values, dp, flag), searchMemory(idx - 3, values, dp, flag)) + + values[idx - 1]), + Math.max(searchMemory(idx - 3, values, dp, flag), searchMemory(idx - 4, values, dp, flag)) + + values[idx - 1] + values[idx - 2]); + } + flag[idx] = true; + return dp[idx]; + } +} diff --git a/Algorithm-Java/src/Lintcode/NestedIterator.java b/Algorithm-Java/src/Lintcode/NestedIterator.java new file mode 100644 index 0000000..b9079b5 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/NestedIterator.java @@ -0,0 +1,61 @@ +package Lintcode; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.sun.glass.ui.TouchInputSupport; +import com.sun.org.apache.bcel.internal.generic.NEW; +import com.sun.org.apache.xalan.internal.xsltc.compiler.Template; + + +interface NestedInteger { + + // @return true if this NestedInteger holds a single integer, + // rather than a nested list. + public boolean isInteger(); + + // @return the single integer that this NestedInteger holds, + // if it holds a single integer + // Return null if this NestedInteger holds a nested list + public Integer getInteger(); + + // @return the nested list that this NestedInteger holds, + // if it holds a nested list + // Return null if this NestedInteger holds a single integer + public List getList(); +} + +public class NestedIterator implements Iterator { + + List nestedList; + List index; + + public NestedIterator(List nestedList) { + this.nestedList = nestedList; + this.index =new ArrayList(); + } + + + // @return {int} the next element in the iteration + @Override + public Integer next() { + return 0; + } + + // @return {boolean} true if the iteration has more element or false + @Override + public boolean hasNext() { + return false; + } + + @Override + public void remove() { + } +} + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i = new NestedIterator(nestedList); while (i.hasNext()) + * v.add(i.next()); + */ \ No newline at end of file diff --git a/Algorithm-Java/src/Lintcode/Util/HashHeap.java b/Algorithm-Java/src/Lintcode/Util/HashHeap.java new file mode 100644 index 0000000..539df17 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Util/HashHeap.java @@ -0,0 +1,166 @@ +package Lintcode.Util; + +import java.util.ArrayList; +import java.util.HashMap; + +class HeapNode{ + int pos_; + int cnt_; + public HeapNode(int pos, int cnt) { + this.pos_ = pos; + this.cnt_ = cnt; + } +} + +public class HashHeap { + + private ArrayList heap_; + private HashMap hash_; + private boolean is_max_; + private int size_; + + public HashHeap(boolean is_max){ + this.heap_ = new ArrayList(); + this.hash_ = new HashMap(); + this.is_max_ = is_max; + } + + //==============================implementation functions==============================// + + public void push(int value) { + if(this.hash_.containsKey(value)){ + HeapNode node = this.hash_.get(value); + node.cnt_++; + }else{ + this.heap_.add(value); + this.hash_.put(value, new HeapNode(this.heap_.size() - 1, 1)); + rise(this.heap_.size() - 1); + } + ++this.size_; + } + + public int poll(){ + int value = this.heap_.get(0); + HeapNode node = this.hash_.get(value); + if(node.cnt_ == 1){ + swap(0, this.heap_.size() - 1); + this.heap_.remove(this.heap_.size() - 1); + this.hash_.remove(value); + sink(0); + }else{ + node.cnt_--; + } + --this.size_; + return value; + } + + public int peek(){ + int value = this.heap_.get(0); + return value; + } + + public void delete(int value) { + HeapNode node = this.hash_.get(value); + if(node.cnt_ == 1){ + int idx = node.pos_; + swap(idx, this.heap_.size() - 1); + this.hash_.remove(value); + this.heap_.remove(this.heap_.size() - 1); + if(idx == heap_.size() - 1){ + rise(idx); + sink(idx); + } + }else{ + node.cnt_--; + } + --this.size_; + } + + public int getSize(){ + return this.size_; + } + + public void sink(int idx){ + while (true) { + int left_idx = getLeftChild(idx); + int right_idx = getRightChild(idx); + int son_idx = idx; + if (left_idx < this.heap_.size() && isPrior(left_idx, idx)) { + son_idx = left_idx; + } + if (right_idx < this.heap_.size() && isPrior(right_idx, idx)) { + son_idx = right_idx; + } + if (son_idx == idx) { + break; + }else{ + swap(son_idx, idx); + } + } + } + + public void rise(int idx){ + while (getParent(idx) != idx) { + int parent_idx = getParent(idx); + if(isPrior(idx, parent_idx)){ + swap(idx, parent_idx); + idx = parent_idx; + }else{ + break; + } + } + } + + //==============================helper functions==============================// + public int getLeftChild(int i){ + return i * 2 + 1; + } + + public int getRightChild(int i){ + return i * 2 + 2; + } + + public int getParent(int i) { + return (i - 1)/2; + } + + public void swap(int i, int j) { + int val_i = heap_.get(i); + int val_j = heap_.get(j); + int cnt_i = hash_.get(val_i).cnt_; + int cnt_j = hash_.get(val_j).cnt_; + + heap_.set(i, val_j); + heap_.set(j, val_i); + hash_.put(val_i, new HeapNode(j, cnt_i)); + hash_.put(val_j, new HeapNode(i, cnt_j)); + } + + public boolean isPrior(int left, int right){ + if(this.is_max_){ + return heap_.get(left) >= heap_.get(right); + }else{ + return heap_.get(left) <= heap_.get(right); + } + } + + public static void main(String[] args) { + HashHeap hh = new HashHeap(true); + hh.push(3); + hh.push(4); + hh.push(3); + hh.push(4); + hh.push(3); + hh.push(4); + + hh.delete(4); + hh.delete(3); + hh.delete(4); + hh.delete(4); + hh.delete(3); + hh.delete(3); + while (hh.getSize() != 0) { + System.out.println(hh.poll()); + } + } +} diff --git a/Algorithm-Java/src/Lintcode/Util/SegmentTree.java b/Algorithm-Java/src/Lintcode/Util/SegmentTree.java new file mode 100644 index 0000000..39e602c --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Util/SegmentTree.java @@ -0,0 +1,155 @@ +package Lintcode.Util; +/* + * http://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/ + * http://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/ + */ + +public class SegmentTree{ + public SegmentTree(int[] arr){ + + } + +} + +//Java Program to show segment tree operations like construction, +//query and update +class SegmentTreeSample { + int st[]; // The array that stores segment tree nodes + + /* + * Constructor to construct segment tree from given array. This constructor + * allocates memory for segment tree and calls constructSTUtil() to fill the + * allocated memory + */ + SegmentTreeSample(int arr[], int n) { + // Allocate memory for segment tree + // Height of segment tree + int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); + + // Maximum size of segment tree + int max_size = 2 * (int) Math.pow(2, x) - 1; + + st = new int[max_size]; // Memory allocation + + constructSTUtil(arr, 0, n - 1, 0); + } + + // A utility function to get the middle index from corner indexes. + int getMid(int s, int e) { + return s + (e - s) / 2; + } + + /* + * A recursive function to get the sum of values in given range of the + * array. The following are parameters for this function. + * + * st --> Pointer to segment tree si --> Index of current node in the + * segment tree. Initially 0 is passed as root is always at index 0 ss & se + * --> Starting and ending indexes of the segment represented by current + * node, i.e., st[si] qs & qe --> Starting and ending indexes of query range + */ + int getSumUtil(int ss, int se, int qs, int qe, int si) { + // If segment of this node is a part of given range, then return + // the sum of the segment + if (qs <= ss && qe >= se) + return st[si]; + + // If segment of this node is outside the given range + if (se < qs || ss > qe) + return 0; + + // If a part of this segment overlaps with the given range + int mid = getMid(ss, se); + return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); + } + + /* + * A recursive function to update the nodes which have the given index in + * their range. The following are parameters st, si, ss and se are same as + * getSumUtil() i --> index of the element to be updated. This index is in + * input array. diff --> Value to be added to all nodes which have i in + * range + */ + void updateValueUtil(int ss, int se, int i, int diff, int si) { + // Base Case: If the input index lies outside the range of + // this segment + if (i < ss || i > se) + return; + + // If the input index is in range of this node, then update the + // value of the node and its children + st[si] = st[si] + diff; + if (se != ss) { + int mid = getMid(ss, se); + updateValueUtil(ss, mid, i, diff, 2 * si + 1); + updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); + } + } + + // The function to update a value in input array and segment tree. + // It uses updateValueUtil() to update the value in segment tree + void updateValue(int arr[], int n, int i, int new_val) { + // Check for erroneous input index + if (i < 0 || i > n - 1) { + System.out.println("Invalid Input"); + return; + } + + // Get the difference between new value and old value + int diff = new_val - arr[i]; + + // Update the value in array + arr[i] = new_val; + + // Update the values of nodes in segment tree + updateValueUtil(0, n - 1, i, diff, 0); + } + + // Return sum of elements in range from index qs (quey start) to + // qe (query end). It mainly uses getSumUtil() + int getSum(int n, int qs, int qe) { + // Check for erroneous input values + if (qs < 0 || qe > n - 1 || qs > qe) { + System.out.println("Invalid Input"); + return -1; + } + return getSumUtil(0, n - 1, qs, qe, 0); + } + + // A recursive function that constructs Segment Tree for array[ss..se]. + // si is index of current node in segment tree st + int constructSTUtil(int arr[], int ss, int se, int si) { + // If there is one element in array, store it in current node of + // segment tree and return + if (ss == se) { + st[si] = arr[ss]; + return arr[ss]; + } + + // If there are more than one elements, then recur for left and + // right subtrees and store the sum of values in this node + int mid = getMid(ss, se); + st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); + return st[si]; + } + + // Driver program to test above functions + public static void main(String args[]) { + int arr[] = { 1, 3, 5, 7, 9, 11 }; + int n = arr.length; + SegmentTreeSample tree = new SegmentTreeSample(arr, n); + + // Build segment tree from given array + + // Print sum of values in array from index 1 to 3 + System.out.println("Sum of values in given range = " + tree.getSum(n, 1, 3)); + + // Update: set arr[1] = 10 and update corresponding segment + // tree nodes + tree.updateValue(arr, n, 1, 10); + + // Find sum after the value is updated + System.out.println("Updated sum of values in given range = " + tree.getSum(n, 1, 3)); + } +} +// This code is contributed by Ankur Narain Verma diff --git a/Algorithm-Java/src/Lintcode/Util/Trie.java b/Algorithm-Java/src/Lintcode/Util/Trie.java new file mode 100644 index 0000000..2b96e72 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Util/Trie.java @@ -0,0 +1,14 @@ +package Lintcode.Util; + +import java.util.HashMap; + +public class Trie { + public boolean marked; + public HashMap children; + + public Trie(){ + this.children = new HashMap(); + } + + +} diff --git a/Algorithm-Java/src/Lintcode/Util/UnionFind.java b/Algorithm-Java/src/Lintcode/Util/UnionFind.java new file mode 100644 index 0000000..a042756 --- /dev/null +++ b/Algorithm-Java/src/Lintcode/Util/UnionFind.java @@ -0,0 +1,82 @@ +package Lintcode.Util; + +public class UnionFind { + + int[] arr; + + public void setVal(int ind, int val){ + this.arr[ind] = val; + } + + public int getVal(int ind){ + return this.arr[ind]; + } + + public UnionFind(int[] arr){ + this.arr = arr; + } + + public UnionFind(int n){ + this.arr = new int[n]; + for (int i = 0; i < n; i++) { + this.arr[i] = i; + } + } + + public int find(int ind) { + while (true) { + int father = this.arr[ind]; + if (father == ind) { + return ind; + }else{ + ind = father; + } + } + } + + public int compressed_find(int ind){ + int root = find(ind); + while (true) { + int father = this.arr[ind]; + if(father == ind){ + break; + }else{ + this.arr[ind] = root; + ind = father; + } + } + return root; + } + + public void merge(int ind1, int ind2) { + int father1 = find(ind1), father2 = find(ind2); + if (father1 < father2) { + this.arr[father2] = father1; + }else{ + this.arr[father1] = father2; + } + } + + public void compressed_merge(int ind1, int ind2) { + int father1 = compressed_find(ind1), father2 = compressed_find(ind2); + if (father1 < father2) { + this.arr[father2] = father1; + }else{ + this.arr[father1] = father2; + } + } + + + public static void main(String[] args) { + UnionFind uFind = new UnionFind(10); + uFind.merge(0, 1); + uFind.merge(0, 3); + System.out.println(uFind.find(1)); + System.out.println(uFind.find(2)); + + uFind.compressed_merge(4, 5); + uFind.compressed_merge(5, 9); + System.out.println(uFind.compressed_find(9)); + System.out.println(uFind.compressed_find(8)); + } +} diff --git a/Algorithm-Java/src/Solution.java b/Algorithm-Java/src/Solution.java new file mode 100644 index 0000000..0d3405f --- /dev/null +++ b/Algorithm-Java/src/Solution.java @@ -0,0 +1,97 @@ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + static String processE(String line) { + StringBuilder temp = new StringBuilder(); + boolean process_flag = false; + for (int i = line.length() - 1; i >= 3; i--) { + char ch = line.charAt(i); + if (process_flag) { + temp.insert(0, ch); + break; + } else { + temp.insert(0, ch); + } + if (ch == '@') { + process_flag = true; + } + } + for (int i = 0; i < 5; i++) { + temp.insert(0, "*"); + } + temp.insert(0, line.charAt(2)); + temp.insert(0, "E:"); + return temp.toString(); + } + + static String processP(String line) { + StringBuilder temp = new StringBuilder(); + int i = line.length() - 1; + for (; i >= line.length() - 4; i--) { + char ch = line.charAt(i); + temp.insert(0, ch); + } + int cnt = 6; + temp.insert(0, "***-***-"); + for (; i >= 2; i--) { + char ch = line.charAt(i); + if (ch >= '0' && ch <= '9') { + --cnt; + if (cnt == 0) { + --i; + break; + } + } + } + boolean process_flag = true; + for (; i >= 2; i--) { + char ch = line.charAt(i); + if (ch >= '0' && ch <= '9') { + temp.insert(0, "*"); + process_flag = true; + } else if (ch == '+') { + temp.insert(0, ch); + process_flag = true; + } else { + if (process_flag) { + temp.insert(0, "-"); + process_flag = false; + } + } + } + if (temp.toString().startsWith("-")) { + temp.deleteCharAt(0); + } + temp.insert(0, "P:"); + return temp.toString(); + } + + public static void main(String args[]) throws Exception { + Scanner scan = new Scanner(System.in); + String line = null; + + StringBuilder sBuilder = new StringBuilder(); + + while (scan.hasNextLine()) { + line = scan.nextLine(); + if (line.length() == 0) { + break; + } + + if (line.startsWith("E")) { + sBuilder.append(processE(line)).append("\n"); + } else if (line.startsWith("P")) { + sBuilder.append(processP(line)).append("\n"); + } + } + sBuilder.setLength(sBuilder.length() - 1); + scan.close(); + + System.out.println(sBuilder.toString()); + } +} \ No newline at end of file diff --git a/Algorithm-Java/src/temp/ReplaceWhiteSpace.java b/Algorithm-Java/src/temp/ReplaceWhiteSpace.java new file mode 100644 index 0000000..1463c3a --- /dev/null +++ b/Algorithm-Java/src/temp/ReplaceWhiteSpace.java @@ -0,0 +1,33 @@ +package temp; + +public class ReplaceWhiteSpace { + void replace(char[] input) { + int loop_idx = 0, append_idx = 0; + while (loop_idx < input.length) { + if (loop_idx != append_idx) { + char temp = input[loop_idx]; + input[loop_idx] = input[append_idx]; + input[append_idx] = temp; + } + + if (input[append_idx] != ' ') { + ++append_idx; + } + + ++loop_idx; + } + } + + public static void main(String[] args) { + char[] input = new char[] { 'a', 'b', ' ', 'c', 'd', ' ', 'e' }; + for (char c : input) { + System.out.println(c); + } + System.out.println("====="); + new ReplaceWhiteSpace().replace(input); + for (char c : input) { + System.out.println(c); + } + System.out.println("====="); + } +} diff --git a/Algorithm-Linux/Algorithm_Linux.1 b/Algorithm-Linux/Algorithm_Linux.1 deleted file mode 100644 index 89f5d4f..0000000 --- a/Algorithm-Linux/Algorithm_Linux.1 +++ /dev/null @@ -1,79 +0,0 @@ -.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. -.\"See Also: -.\"man mdoc.samples for a complete listing of options -.\"man mdoc for the short list of editing options -.\"/usr/share/misc/mdoc.template -.Dd 12/3/12 \" DATE -.Dt Algorithm-Linux 1 \" Program name and manual section number -.Os Darwin -.Sh NAME \" Section Header - required - don't modify -.Nm Algorithm-Linux, -.\" The following lines are read in generating the apropos(man -k) database. Use only key -.\" words here as the database is built based on the words here and in the .ND line. -.Nm Other_name_for_same_program(), -.Nm Yet another name for the same program. -.\" Use .Nm macro to designate other names for the documented program. -.Nd This line parsed for whatis database. -.Sh SYNOPSIS \" Section Header - required - don't modify -.Nm -.Op Fl abcd \" [-abcd] -.Op Fl a Ar path \" [-a path] -.Op Ar file \" [file] -.Op Ar \" [file ...] -.Ar arg0 \" Underlined argument - use .Ar anywhere to underline -arg2 ... \" Arguments -.Sh DESCRIPTION \" Section Header - required - don't modify -Use the .Nm macro to refer to your program throughout the man page like such: -.Nm -Underlining is accomplished with the .Ar macro like this: -.Ar underlined text . -.Pp \" Inserts a space -A list of items with descriptions: -.Bl -tag -width -indent \" Begins a tagged list -.It item a \" Each item preceded by .It macro -Description of item a -.It item b -Description of item b -.El \" Ends the list -.Pp -A list of flags and their descriptions: -.Bl -tag -width -indent \" Differs from above in tag removed -.It Fl a \"-a flag as a list item -Description of -a flag -.It Fl b -Description of -b flag -.El \" Ends the list -.Pp -.\" .Sh ENVIRONMENT \" May not be needed -.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 -.\" .It Ev ENV_VAR_1 -.\" Description of ENV_VAR_1 -.\" .It Ev ENV_VAR_2 -.\" Description of ENV_VAR_2 -.\" .El -.Sh FILES \" File used or created by the topic of the man page -.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact -.It Pa /usr/share/file_name -FILE_1 description -.It Pa /Users/joeuser/Library/really_long_file_name -FILE_2 description -.El \" Ends the list -.\" .Sh DIAGNOSTICS \" May not be needed -.\" .Bl -diag -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .El -.Sh SEE ALSO -.\" List links in ascending order by section, alphabetically within a section. -.\" Please do not reference files that do not exist without filing a bug report -.Xr a 1 , -.Xr b 1 , -.Xr c 1 , -.Xr a 2 , -.Xr b 2 , -.Xr a 3 , -.Xr b 3 -.\" .Sh BUGS \" Document known, unremedied bugs -.\" .Sh HISTORY \" Document history if command behaves in a unique manner \ No newline at end of file diff --git a/Algorithm-Linux/main.cpp b/Algorithm-Linux/main.cpp deleted file mode 100644 index a9aa871..0000000 --- a/Algorithm-Linux/main.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.cpp -// Algorithm-Linux -// -// Created by Sanqiang Zhao on 12/3/12. -// Copyright (c) 2012 Sanqiang Zhao. All rights reserved. -// -#include "main.h" - -int main(int argc, const char * argv[]) -{ - - return 0; -} - - - diff --git a/Algorithm-Linux/main.h b/Algorithm-Linux/main.h deleted file mode 100644 index 070c7ca..0000000 --- a/Algorithm-Linux/main.h +++ /dev/null @@ -1,81 +0,0 @@ -// -// main.h -// Algorithm-Linux -// -// Created by Sanqiang Zhao on 12/3/12. -// Copyright (c) 2012 Sanqiang Zhao. All rights reserved. -// - -#ifndef Algorithm_Linux_main_h -#define Algorithm_Linux_main_h -using namespace std; - -#include -#include "Entity.h" -//chapter 11 -#include "Q111-MergeSortedArray.h" -#include "Q112-SortString.h" -#include "Q113-FindInRotatedArr.h" -#include "Q115-FindStringInIntersperse.h" -#include "Q116-SearchOnMatrix.h" -#include "Q117-LongestIncreasingSequence.h" -#include "Q118-TrackBinarySearchTree.h" -#include "QuickSort.h" -//Chapter 9 -#include "Q91-CountWaysOnStairs.h" -#include "Q92-RobotMovement.h" -#include "Q93-FindMagicIndex.h" -#include "Q94-Subsets.h" -#include "Q95-Permutation.h" -#include "Q96-ValidParenthesis.h" -#include "Q97-FillColor.h" -#include "Q98-MakeCoinCharges.h" -#include "Q99-PlaceQueen.h" -#include "Q910-CreateStackBox.h" -#include "Q911-BinaryPresentation.h" -//Chapter 1 -#include "Q11-VerifyUniqueCharInString.h" -#include "Q12-ReverseString.h" -#include "Q13-VerifyAnagram.h" -#include "Q14-encodeUrl.h" -#include "Q15-compressStr.h" -#include "Q16-rotateMatrix.h" -#include "Q17-SetZeroOnMatrix.h" -#include "Q18-VerifyRotation.h" -#include "KMP.h" -//Chapter 2 -#include "Q21-removeDuplacate.h" -#include "Q22-findLastNthElement.h" -#include "Q23-deleteElement.h" -#include "Q24-PartitionLinkedList.h" -#include "Q25-AddLinkedList.h" -#include "Q26-findEntryInCircularList.h" -#include "Q27-VerifyPalindrome.h" -//Chapter 3 -#include "Q31-ThreeStacksFromOneArray.h" -#include "Q32-StackWithMin.h" -#include "Q33-SetOfStacks.h" -#include "Q34-TowersOfHanoi.h" -#include "Q35-QueueWithTwoStacks.h" -#include "Q36-SortStack.h" -#include "Q37-AnimalShelter.h" -//Chapter 4 -#include "Q41-CheckBalanceTree.h" -#include "Q42-FindRouteBFS.h" -#include "Q43-BinarySearchTreeFromSortedArray.h" -#include "Q44-BuildLinkedListFromTreeBFS.h" -#include "Q45-CheckBinarySearchTree.h" -#include "Q46-NextOnBinaryTree.h" -#include "Q47-FindCommonAncester.h" -#include "Q48-CheckSubTree.h" -#include "Q49-FindSumBFS.h" -//Chapter 5 -#include "Q51-UpdateBitOnMN.h" -#include "Q52-PrintBinary.h" -#include "Q53-NextNumWithSameBit.h" -#include "Q55-BitSwapRequired.h" -#include "Q56-SwapOddEvenBit.h" -#include "Q57-FindMissing.h" -#include "Q58-DrawHorizontalLine.h" - -#endif diff --git a/Algorithm-Python/.DS_Store b/Algorithm-Python/.DS_Store new file mode 100644 index 0000000..27a4a00 Binary files /dev/null and b/Algorithm-Python/.DS_Store differ diff --git a/Algorithm-Python/.idea/.name b/Algorithm-Python/.idea/.name new file mode 100644 index 0000000..3ef01ee --- /dev/null +++ b/Algorithm-Python/.idea/.name @@ -0,0 +1 @@ +Algorithm-Python \ No newline at end of file diff --git a/Algorithm-Python/.idea/Algorithm-Python.iml b/Algorithm-Python/.idea/Algorithm-Python.iml new file mode 100644 index 0000000..d0876a7 --- /dev/null +++ b/Algorithm-Python/.idea/Algorithm-Python.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Algorithm-Python/.idea/misc.xml b/Algorithm-Python/.idea/misc.xml new file mode 100644 index 0000000..492a22a --- /dev/null +++ b/Algorithm-Python/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Algorithm-Python/.idea/modules.xml b/Algorithm-Python/.idea/modules.xml new file mode 100644 index 0000000..8a49202 --- /dev/null +++ b/Algorithm-Python/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Algorithm-Python/.idea/vcs.xml b/Algorithm-Python/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/Algorithm-Python/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Algorithm-Python/.idea/workspace.xml b/Algorithm-Python/.idea/workspace.xml new file mode 100644 index 0000000..26b999f --- /dev/null +++ b/Algorithm-Python/.idea/workspace.xml @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1448472365053 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git "a/Algorithm-Python/book/JavaScript \346\235\203\345\250\201\346\214\207\345\215\227\357\274\210\344\270\255\346\226\207\347\254\2546\347\211\210\357\274\211.pdf" "b/Algorithm-Python/book/JavaScript \346\235\203\345\250\201\346\214\207\345\215\227\357\274\210\344\270\255\346\226\207\347\254\2546\347\211\210\357\274\211.pdf" new file mode 100644 index 0000000..417d3ca Binary files /dev/null and "b/Algorithm-Python/book/JavaScript \346\235\203\345\250\201\346\214\207\345\215\227\357\274\210\344\270\255\346\226\207\347\254\2546\347\211\210\357\274\211.pdf" differ diff --git "a/Algorithm-Python/book/JavaScript\351\253\230\347\272\247\347\250\213\345\272\217\350\256\276\350\256\241\357\274\210\347\254\2543\347\211\210\357\274\211\343\200\221\344\270\255\346\226\207 \351\253\230\346\270\205 \345\256\214\346\225\264 \350\257\246\347\273\206\344\271\246\347\255\276\347\211\210.pdf" "b/Algorithm-Python/book/JavaScript\351\253\230\347\272\247\347\250\213\345\272\217\350\256\276\350\256\241\357\274\210\347\254\2543\347\211\210\357\274\211\343\200\221\344\270\255\346\226\207 \351\253\230\346\270\205 \345\256\214\346\225\264 \350\257\246\347\273\206\344\271\246\347\255\276\347\211\210.pdf" new file mode 100644 index 0000000..367ebd4 Binary files /dev/null and "b/Algorithm-Python/book/JavaScript\351\253\230\347\272\247\347\250\213\345\272\217\350\256\276\350\256\241\357\274\210\347\254\2543\347\211\210\357\274\211\343\200\221\344\270\255\346\226\207 \351\253\230\346\270\205 \345\256\214\346\225\264 \350\257\246\347\273\206\344\271\246\347\255\276\347\211\210.pdf" differ diff --git a/Algorithm-Python/class/largest-sum-contiguous-subarray.py b/Algorithm-Python/class/largest-sum-contiguous-subarray.py new file mode 100644 index 0000000..a17946e --- /dev/null +++ b/Algorithm-Python/class/largest-sum-contiguous-subarray.py @@ -0,0 +1,15 @@ +def maxSubArraySum(a,size): + max_value = a[0] + max_sofar = max(0, a[0]) + for i in range(1, size): + if max_sofar + a[i] > 0: + max_sofar = max_sofar + a[i] + else: + max_sofar = 0 + max_value = max(max_sofar, max_value) + + print(max_value) + +if __name__ == '__main__': + a = [-2, -3, 4, -1, -2, 1, 5, -3] + maxSubArraySum(a, len(a)) \ No newline at end of file diff --git a/Algorithm-Python/lintcode/__init__.py b/Algorithm-Python/lintcode/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Algorithm-Python/lintcode/a-b-problem.py b/Algorithm-Python/lintcode/a-b-problem.py new file mode 100644 index 0000000..72e5349 --- /dev/null +++ b/Algorithm-Python/lintcode/a-b-problem.py @@ -0,0 +1,58 @@ +import sys + +class Solution: + """ + @param a: The first integer + @param b: The second integer + @return: The sum of a and b + """ + def aplusb(self, a, b): + # write your code here, try to do it without arithmetic operators. + method = "seq" + if method == "xor": + while b > 0: + sum = a^b + carry = (a&b)<<1 + a = sum + b = carry + return sum + elif method == "seq": #todo : http://stackoverflow.com/questions/37135106/what-is-good-way-to-negate-an-integer-in-binary-operation-in-python + len = sys.getsizeof(a) + mask_sign = 1<<(len-1) + + neg = False + if ((a<0 and b>0 and abs(a)>abs(b)) or (a>0 and b<0 and abs(a) k: + end = pivot_idx-1 + else: + start = pivot_idx+1 + + def partition(self, A, start, end): + pivot = A[math.floor((start+end)/2)] + while start < end: + for start in range(start,end+1,1): + if A[start] <= pivot: + break + for end in range(end,start-1,-1): + if A[end] >= pivot: + break + if start < end: + self.swap(A,start,end) + start+=1 + end-=1 + return start + + def swap(self,A,i,j): + temp = A[i] + A[i] = A[j] + A[j] = temp + +sol = Solution() +kl = sol.kthLargestElement(4,[3,5,2,3,1]) +print(kl) \ No newline at end of file diff --git a/Algorithm-Python/lintcode/trailing-zeros.py b/Algorithm-Python/lintcode/trailing-zeros.py new file mode 100644 index 0000000..c9012eb --- /dev/null +++ b/Algorithm-Python/lintcode/trailing-zeros.py @@ -0,0 +1,14 @@ +class Solution: + # @param n a integer + # @return ans a integer + def trailingZeros(self, n): + zero_count = 0 + while n != 0: + n /= 5 + zero_count += 1 + return zero_count + + +solu = Solution() +z = solu.trailingZeros(10) +print(z) \ No newline at end of file diff --git a/Algorithm-Python/lintcode/ugly-number-ii.py b/Algorithm-Python/lintcode/ugly-number-ii.py new file mode 100644 index 0000000..95718ed --- /dev/null +++ b/Algorithm-Python/lintcode/ugly-number-ii.py @@ -0,0 +1,58 @@ +import heapq + +class Solution: + """ + @param {int} n an integer. + @return {int} the nth prime number as description. + """ + def nthUglyNumber(self, n): + # write your code here + method = "mex" + if method == "me": + if n <= 1: + return 1 + n -= 1 + heap = [] + dup = {2:True,3:True,5:True} + heapq.heappush(heap,2) + heapq.heappush(heap,3) + heapq.heappush(heap,5) + + while True: + cur = heapq.heappop(heap) + n -= 1 + if n == 0: + return cur + else: + if cur*2 not in dup: + heapq.heappush(heap,2 * cur) + dup[cur * 2] = True + if cur*3 not in dup: + heapq.heappush(heap,3 * cur) + dup[cur * 3] = True + if cur*5 not in dup: + heapq.heappush(heap,5 * cur) + dup[cur * 5] = True + else: + if n <= 1: + return n + + n -= 1 + key = [2, 3, 5] + h = [] + for i in range(3): + heapq.heappush(h, (key[i], i)) + + value = key[0] + while n > 0: + value, level = heapq.heappop(h) + while level < 3: + new_value = key[level] * value + heapq.heappush(h, (new_value, level)) + level += 1 + n -= 1 + return value + +sol = Solution() +n = sol.nthUglyNumber(9) +print(n) \ No newline at end of file diff --git a/Algorithm-Python/minimum-depth-of-binary-tree.py b/Algorithm-Python/minimum-depth-of-binary-tree.py new file mode 100644 index 0000000..dc47385 --- /dev/null +++ b/Algorithm-Python/minimum-depth-of-binary-tree.py @@ -0,0 +1,95 @@ +from Queue import Queue +# Definition for a binary tree node. +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution(object): + def minDepth2(self, root): + """ + :type root: TreeNode + :rtype: int + """ + if root is None: + return 0 + elif root.left is None and root.right is None: + return 1 + else: + ll = root.left is not None + rr = root.right is not None + + if ll and rr: + return 1+min(self.minDepth(root.left), self.minDepth(root.right)) + elif rr: + return 1+self.minDepth(root.right) + elif ll: + return 1+self.minDepth(root.left) + + + def minDepth3(self, root): + """ + :type root: TreeNode + :rtype: int + """ + if root is None: + return 0 + + q_odd = list() + q_even = list() + q_odd.append(root) + level = 1 + while True: + if level % 2 == 1: #for odd + del q_even[:] + for node in q_odd: + ll = node.left is None + rr = node.right is None + if ll and rr: + return level + else: + if not ll: + q_even.append(node.left) + if not rr: + q_even.append(node.right) + else: #for even + del q_odd[:] + for node in q_even: + ll = node.left is None + rr = node.right is None + if ll and rr: + return level + else: + if not ll: + q_odd.append(node.left) + if not rr: + q_odd.append(node.right) + level += 1 + + def minDepth(self, root): + if root is None: + return 0 + q = Queue() + q.put(root) + next_num = 0 + cur_num = 1 + level = 0 + while not q.empty(): + node = q.get() + cur_num -= 1 + ll = node.left is None + rr = node.right is None + if ll and rr: + return level + if not ll: + q.put(node.left) + next_num += 1 + if not rr: + q.put(node.right) + next_num += 1 + if cur_num == 0: + cur_num = next_num + next_num = 0 + level += 1 + diff --git a/Algorithm-Python/util/__pycache__/tree.cpython-35.pyc b/Algorithm-Python/util/__pycache__/tree.cpython-35.pyc new file mode 100644 index 0000000..caf69dd Binary files /dev/null and b/Algorithm-Python/util/__pycache__/tree.cpython-35.pyc differ diff --git a/Algorithm-Python/util/heapq.py b/Algorithm-Python/util/heapq.py new file mode 100644 index 0000000..ac02be4 --- /dev/null +++ b/Algorithm-Python/util/heapq.py @@ -0,0 +1,57 @@ +from util.tree import tree_arr + +class heapq: + def __init__(self, arr): + self.tree = tree_arr(arr) + + def push(self, element): + self.tree.append(element) + loop_idx = self.tree.size()-1 + while loop_idx > 0: + change_idx = loop_idx + if self.tree.parent(change_idx) is not None and self.tree.arr[self.tree.parent(loop_idx)] < self.tree.arr[loop_idx]: + change_idx = self.tree.parent(loop_idx) + if change_idx != loop_idx: + self.tree.swap(change_idx, loop_idx) + loop_idx = self.tree.parent(loop_idx) + else: + break + + def pop(self): + + loop_idx = 0 + while True: + min_idx = -1 + if self.tree.left_child(loop_idx) is not None and self.tree.right_child(loop_idx) is not None: + if self.tree.arr[self.tree.left_child(loop_idx)] > self.tree.arr[self.tree.right_child(loop_idx)]: + min_idx = self.tree.left_child(loop_idx) + else: + min_idx = self.tree.right_child(loop_idx) + elif self.tree.left_child(loop_idx) is not None: + min_idx = self.tree.left_child(loop_idx) + elif self.tree.right_child(loop_idx) is not None: + min_idx = self.tree.right_child(loop_idx) + else: + break + self.tree.swap(loop_idx, min_idx) + loop_idx = min_idx + self.tree.swap(loop_idx, self.tree.size()-1) + temp = self.tree.remove(self.tree.size()-1) + return temp + +q = heapq([]) +q.push(3) +q.push(4) +q.push(1) +q.push(2) +q.push(9) +q.push(91) + +x = q.pop() +print(x) +x = q.pop() +print(x) +x = q.pop() +print(x) +x = q.pop() +print(x) \ No newline at end of file diff --git a/Algorithm-Python/util/range-binary-search-tree.py b/Algorithm-Python/util/range-binary-search-tree.py new file mode 100644 index 0000000..ba21baf --- /dev/null +++ b/Algorithm-Python/util/range-binary-search-tree.py @@ -0,0 +1,21 @@ +from util.tree import tree_arr + + +def rangeBinarySearchTreeDFS(root, idx, s, e, solutions = []): + val = root.get_value(idx) + if val >= s and val <= e: + solutions.append(val) + if val >= s and root.contain_left_child(idx): + rangeBinarySearchTreeDFS(root, root.left_child(idx), s, e, solutions) + if val <= e and root.contain_right_child(idx): + rangeBinarySearchTreeDFS(root, root.right_child(idx), s, e, solutions) + return + +if __name__ == '__main__': + root = tree_arr([5,3,9,1,4,6,10]) + solutions = [] + rangeBinarySearchTreeDFS(root, 0, 3, 6, solutions) + for i in solutions: + print(i) + print("\t") + diff --git a/Algorithm-Python/util/segment_tree.py b/Algorithm-Python/util/segment_tree.py new file mode 100644 index 0000000..94543b6 --- /dev/null +++ b/Algorithm-Python/util/segment_tree.py @@ -0,0 +1,3 @@ +#http://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/ +#http://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/ + diff --git a/Algorithm-Python/util/tree.py b/Algorithm-Python/util/tree.py new file mode 100644 index 0000000..7796c9b --- /dev/null +++ b/Algorithm-Python/util/tree.py @@ -0,0 +1,42 @@ +import math + +class tree_arr: + def __init__(self, arr): + self.arr = arr + + def get_value(self, i): + return self.arr[i] + + def contain_left_child(self, idx): + return 2*idx + 1 < self.size() + + def contain_right_child(self, idx): + return 2*idx + 2 < self.size() + + def left_child(self, idx): + if 2*idx + 1 < self.size(): + return 2*idx + 1 + + def right_child(self,idx): + if 2*idx + 2 < self.size(): + return 2*idx + 2 + + def parent(self, idx): + if idx > 0: + return math.floor((idx-1)/2) + + def append(self, element): + self.arr.append(element) + + def remove(self, idx): + temp = self.arr[idx] + self.arr.pop(idx) + return temp + + def size(self): + return len(self.arr) + + def swap(self, index1, index2): + temp = self.arr[index1] + self.arr[index1] = self.arr[index2] + self.arr[index2] = temp \ No newline at end of file diff --git a/Algorithm-Python/word-search.py b/Algorithm-Python/word-search.py new file mode 100644 index 0000000..a66251f --- /dev/null +++ b/Algorithm-Python/word-search.py @@ -0,0 +1,42 @@ +class Solution(object): + def existRecursive(self, board, word, row, col,nrow,ncol, ind,nword): + + if board[row][col] == word[ind]: + temp = board[row][col] + board[row][col] = '*' + if ind == nword - 1: + return True + elif (row + 1 < nrow and board[row + 1][col] != '*' and self.existRecursive(board, word, row + 1, col,nrow,ncol, + ind + 1,nword)) or ( + row - 1 >= 0 and board[row - 1][col] != '*' and self.existRecursive(board, word, row - 1, + col,nrow,ncol, + ind + 1,nword)) or ( + col + 1 < ncol and board[row][col + 1] != '*' and self.existRecursive(board, word, row, + col + 1,nrow,ncol, + ind + 1,nword)) or ( + col - 1 >= 0 and board[row][col - 1] != '*' and self.existRecursive(board, word, row, + col - 1,nrow,ncol, + ind + 1,nword)): + return True + board[row][col] = temp + else: + return False + + def exist(self, board, word): + """ + :type board: List[List[str]] + :type word: str + :rtype: bool + """ + nrow = len(board) + ncol = len(board[0]) + nword = len(word) + + for row in range(0, nrow): + for col in range(0, ncol): + if board[row][col] == word[0] and self.existRecursive(board, word, row, col,nrow,ncol, 0,nword): + return True + return False + + +s = Solution() diff --git a/Sample/.DS_Store b/Sample/.DS_Store index 12f56d5..13f41ea 100644 Binary files a/Sample/.DS_Store and b/Sample/.DS_Store differ