├── .gitignore ├── src ├── 172.c ├── 136.c ├── 70.c ├── 171.c ├── 9.c ├── 58.c ├── 35.c ├── 258.c ├── 62.c ├── 26.c ├── 50.c ├── 209.c ├── 96.c ├── 119.c ├── 153.c ├── 169.c ├── 27.c ├── 154.c ├── 268.c ├── 89.c ├── 134.c ├── 168.c ├── 263.c ├── 223.c ├── 231.c ├── 198.c ├── 53.c ├── 122.c ├── 152.c ├── 233.c ├── 66.c ├── 278.c ├── 162.c ├── 237.c ├── 242.c ├── 80.c ├── 33.c ├── 14.c ├── 264.c ├── 129.c ├── 299.c ├── 41.c ├── 91.c ├── 204.c ├── 22.cpp ├── 77.cpp ├── 213.c ├── 115.c ├── 63.c ├── 292.c ├── 88.c ├── 7.c ├── 104.c ├── 139.cpp ├── 313.c ├── 216.cpp ├── 120.c ├── 67.c ├── 205.c ├── 52.c ├── 93.cpp ├── 43.c ├── 8.c ├── 260.c ├── 118.c ├── 238.c ├── 116.c ├── 142.c ├── 144.cpp ├── 64.c ├── 257.cpp ├── 141.c ├── 5.cpp ├── 34.cpp ├── 279.c ├── 189.c ├── 83.c ├── 241.cpp ├── 112.c ├── 111.c ├── 59.c ├── 38.c ├── 81.c ├── 151.c ├── 24.c ├── 164.c ├── 48.c ├── 13.c ├── 222.c ├── 39.cpp ├── 131.cpp ├── 100.c ├── 240.c ├── 114.c ├── 69.c ├── 86.c ├── 290.cpp ├── 60.cpp ├── 105.c ├── 125.c ├── 228.c ├── 61.c ├── 173.cpp ├── 6.c ├── 106.c ├── 19.c ├── 217.c ├── 78.cpp ├── 101.c ├── 179.c ├── 200.c ├── 31.c ├── 190.c ├── 74.c ├── 300.c ├── 132.cpp ├── 109.cpp ├── 72.c ├── 82.c ├── 206.c ├── 113.cpp ├── 127.cpp ├── 203.c ├── 79.c ├── 20.c ├── 201.c ├── 90.cpp ├── 40.cpp ├── 150.c ├── 283.c ├── 236.cpp ├── 275.c ├── 75.c ├── 12.c ├── 110.c ├── 235.c ├── 165.c ├── 92.c ├── 17.cpp ├── 107.cpp ├── 133.cpp ├── 143.c ├── 148.c ├── 51.cpp ├── 54.c ├── 219.c └── 147.c └── Makefile /.gitignore: -------------------------------------------------------------------------------- 1 | # Executables 2 | *.exe 3 | *.out 4 | 5 | # Files without extension 6 | src/* 7 | !src/*.* 8 | -------------------------------------------------------------------------------- /src/172.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int trailingZeroes(int n) { 4 | int c = 0; 5 | while (n) { 6 | n /= 5; 7 | c += n; 8 | } 9 | return c; 10 | } 11 | 12 | int main() { 13 | printf("%d\n", trailingZeroes(1808548329)); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /src/136.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int singleNumber(int A[], int n) { 6 | int one = 0; 7 | int i; 8 | for (i = 0; i < n; i++) { 9 | one = one ^ A[i]; 10 | } 11 | return one; 12 | } 13 | 14 | int main() 15 | { 16 | int A[] = {1, 2, 1, 3, 4, 3, 4}; 17 | printf("%d\n", singleNumber(A, sizeof(A)/sizeof(A[0]))); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /src/70.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int climbStairs(int n) { 5 | if (n < 3) return n; 6 | int *d = (int *)calloc(n, sizeof(int)); 7 | int i; 8 | d[0] = 1; 9 | d[1] = 2; 10 | for (i = 2; i < n; i++) { 11 | d[i] = d[i - 1] + d[i - 2]; 12 | } 13 | return d[n - 1]; 14 | } 15 | 16 | int main() { 17 | printf("%d\n", climbStairs(10)); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CXX = g++ 3 | CFLAGS = -std=c99 -Wall -lm 4 | CXXFLAGS = -std=c++11 -Wall 5 | 6 | C_SRCS = $(wildcard src/*.c) 7 | C_OUTS = $(patsubst %.c, %, $(C_SRCS)) 8 | CXX_SRCS = $(wildcard src/*.cpp) 9 | CXX_OUTS = $(patsubst %.cpp, %, $(CXX_SRCS)) 10 | 11 | .PHONY: clean 12 | 13 | all: $(C_OUTS) $(CXX_OUTS) 14 | 15 | %.out : %.c 16 | $(CC) $(CFLAGS) $< -o $@ 17 | 18 | %.out : %.cpp 19 | $(CXX) $(CXXFLAGS) $< -o $@ 20 | 21 | clean: 22 | $(RM) $(C_OUTS) $(CXX_OUTS) 23 | -------------------------------------------------------------------------------- /src/171.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int titleToNumber(char *s) { 5 | int len = strlen(s); 6 | int i = 0; 7 | int ans = 0; 8 | while (i < len) { 9 | ans = ans * 26 + s[i] - 'A' + 1; 10 | i++; 11 | } 12 | 13 | return ans; 14 | } 15 | 16 | int main() { 17 | char s1[] = "Z"; 18 | char s2[] = "AB"; 19 | 20 | printf("%d\n", titleToNumber(s1)); 21 | printf("%d\n", titleToNumber(s2)); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /src/9.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | bool isPalindrome(int x) { 5 | if (x < 0) return false; 6 | 7 | int t = x; 8 | int mask = 1; 9 | while (t >= 10) { 10 | mask *= 10; 11 | t /= 10; 12 | } 13 | 14 | int l, r; 15 | while (x) { 16 | r = x % 10; 17 | l = x / mask; 18 | if (l != r) return false; 19 | x = (x % mask) / 10; 20 | mask /= 100; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | int main(){ 27 | int a = 1234321; 28 | printf("%d\n", isPalindrome(a)); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /src/58.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int lengthOfLastWord(char* s) { 5 | if (s == NULL) return 0; 6 | int len = strlen(s); 7 | if (len == 0) return 0; 8 | 9 | int count = 0; 10 | int i; 11 | for (i = len - 1; i >= 0; i--) { 12 | if (s[i] == ' ') { 13 | if (count == 0) continue; 14 | else break; 15 | } 16 | count++; 17 | } 18 | 19 | return count; 20 | } 21 | 22 | int main() { 23 | char s[] = "Hello World "; 24 | /* should be 5 */ 25 | printf("%d\n", lengthOfLastWord(s)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/35.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int searchInsert(int A[], int n, int target) { 4 | int l, r, m; 5 | l = 0; 6 | r = n - 1; 7 | while (l <= r) { 8 | m = (l + r) / 2; 9 | if (A[m] == target) { 10 | return m; 11 | } 12 | else if (A[m] < target) { 13 | l = m + 1; 14 | } 15 | else { 16 | r = m - 1; 17 | } 18 | } 19 | return l; 20 | } 21 | 22 | int main() { 23 | int num[] = {1}; 24 | /* should be 1 */ 25 | printf("%d\n", searchInsert(num, sizeof(num)/sizeof(num[0]), 4)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/258.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int addDigits0(int num) { 5 | int ans = 0; 6 | while (num > 0) { 7 | ans += num % 10; 8 | num /= 10; 9 | if (ans >= 10) { 10 | ans = ans / 10 + ans % 10; 11 | } 12 | } 13 | return ans; 14 | } 15 | 16 | int addDigits(int num) { 17 | return 1 + (num - 1) % 9; 18 | } 19 | 20 | int main() { 21 | 22 | assert(addDigits(0) == 0); 23 | assert(addDigits(1) == 1); 24 | assert(addDigits(9) == 9); 25 | assert(addDigits(38) == 2); 26 | assert(addDigits(12345) == 6); 27 | 28 | printf("all tests passed!\n"); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /src/62.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int uniquePaths(int m, int n) { 5 | int (*p)[n] = (int (*)[n]) calloc(m * n, sizeof(int)); 6 | p[0][0] = 1; 7 | int i, j; 8 | for (i = 0; i < m; i++) { 9 | for (j = 0; j < n; j++) { 10 | if (i > 0 && j == 0) 11 | p[i][j] = p[i - 1][j]; 12 | if (j > 0 && i == 0) 13 | p[i][j] = p[i][j - 1]; 14 | if (i > 0 && j > 0) 15 | p[i][j] = p[i][j - 1] + p[i - 1][j]; 16 | } 17 | } 18 | 19 | return p[m - 1][n - 1]; 20 | } 21 | 22 | int main(){ 23 | printf("%d\n", uniquePaths(3, 7)); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /src/26.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int removeDuplicates(int A[], int n) { 4 | if (n == 0) return 0; 5 | int i, j; 6 | i = 1, j = 1; 7 | while (j < n) { 8 | while (A[j - 1] == A[j]) { 9 | j++; 10 | if (j >= n) goto OUT; 11 | } 12 | A[i] = A[j]; 13 | i++; 14 | j++; 15 | } 16 | 17 | OUT: 18 | return i; 19 | } 20 | 21 | int main() { 22 | int A[] = { 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5 }; 23 | int new_len = removeDuplicates(A, sizeof(A) / sizeof(A[0])); 24 | 25 | int i; 26 | for (i = 0; i < new_len; i++) { 27 | printf("%d ", A[i]); 28 | } 29 | printf("\n"); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /src/50.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | double myPow(double x, int n) { 4 | if (x == 1 || n == 0) return 1; 5 | if (n == 1) return x; 6 | 7 | double ans = 1.0; 8 | unsigned un; 9 | 10 | un = (n > 0) ? (n) : (-n); 11 | x = (n > 0) ? (x) : (1 / x); 12 | 13 | while (un) { 14 | if (un & 1) { 15 | ans = ans * x; 16 | } 17 | x *= x; 18 | un >>= 1; 19 | } 20 | 21 | return ans; 22 | } 23 | 24 | int main() { 25 | 26 | double x = 9.125; 27 | 28 | printf("%f\n", myPow(x, 1)); 29 | printf("%f\n", myPow(x, 5)); 30 | printf("%f\n", myPow(x, -5)); 31 | printf("%f\n", myPow(1.0, -2147483648)); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /src/209.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int minSubArrayLen(int s, int* nums, int numsSize) { 5 | int i = 0, j = 0; 6 | int sum = 0; 7 | int min = numsSize + 1; 8 | while (j < numsSize) { 9 | sum += nums[j]; 10 | while (sum >= s) { 11 | if (j - i + 1 < min) { 12 | min = j - i + 1; 13 | } 14 | sum -= nums[i]; 15 | i++; 16 | } 17 | j++; 18 | } 19 | 20 | return min == numsSize + 1 ? 0 : min; 21 | } 22 | 23 | int main() { 24 | int nums[] = { 2, 3, 1, 2, 4, 3 }; 25 | assert(minSubArrayLen(7, nums, sizeof(nums) / sizeof(nums[0])) == 2); 26 | 27 | printf("all tests passed\n"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /src/96.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | Catalan Number Catalan(n) = 2(2n-1)/(n+1)*Catalan(n-1) 6 | = C(2n, n)/(n+1) = (2n)!/(n+1)!n! 7 | http://mathworld.wolfram.com/CatalanNumber.html 8 | */ 9 | 10 | int numTrees(int n) { 11 | if (n < 3) return n; 12 | 13 | int *d = (int *) calloc(n + 1, sizeof(int)); 14 | int i, j; 15 | d[0] = 1; /* dummy */ 16 | d[1] = 1; 17 | d[2] = 2; 18 | for (i = 3; i <= n; i++) { 19 | for (j = 0; j < i; j++) { 20 | d[i] += d[j] * d[i - 1 - j]; 21 | } 22 | } 23 | return d[n]; 24 | } 25 | 26 | int main() { 27 | printf("%d\n", numTrees(4)); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /src/119.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int *getRow(int rowIndex) { 5 | int k = rowIndex; 6 | int *ans = (int *)calloc(k + 1, sizeof(int)); 7 | int i, j; 8 | int prev = 0, cur = 0; 9 | ans[0] = 1; 10 | for (i = 1; i < k + 1; i++) { 11 | prev = ans[0]; 12 | for (j = 1; j < i; j++) { 13 | cur = ans[j]; 14 | ans[j] += prev; 15 | prev = cur; 16 | } 17 | ans[i] = 1; 18 | } 19 | return ans; 20 | } 21 | 22 | int main() { 23 | int k = 5; 24 | int *ans = getRow(k); 25 | int i; 26 | for (i = 0; i < k + 1; i++) { 27 | printf("%d ", ans[i]); 28 | } 29 | printf("\n"); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /src/153.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int findMin(int *nums, int numsSize) { 5 | int l = 0; 6 | int r = numsSize - 1; 7 | while (l < r) { 8 | int m = l + (r - l) / 2; 9 | if (nums[l] > nums[m]) { /* right side is sorted */ 10 | r = m; 11 | } 12 | else if (nums[r] < nums[m]) { /* left side is sorted */ 13 | l = m + 1; 14 | } 15 | else { /* the sub-array is not rotated */ 16 | r = m; 17 | } 18 | } 19 | return nums[l]; 20 | } 21 | 22 | int main() { 23 | int nums[] = { 3, 1, 2 }; 24 | 25 | assert(findMin(nums, sizeof(nums) / sizeof(nums[0])) == 1); 26 | 27 | printf("all tests passed!\n"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /src/169.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int majorityElement(int num[], int n) { 4 | int major; 5 | int i; 6 | major = num[0]; 7 | int count = 1; 8 | for (i = 1; i < n; i++) { 9 | if (num[i] == major) count ++; 10 | else count --; 11 | 12 | if (count == 0) { 13 | major = num[i]; 14 | count = 1; 15 | } 16 | } 17 | 18 | return major; 19 | } 20 | 21 | int main() { 22 | 23 | int num1[] = { 1, 2, 2, 3, 3, 3, 3, 4}; 24 | int num2[] = { 4, 5, 4}; 25 | 26 | printf("%d\n", majorityElement(num1, sizeof(num1)/sizeof(num1[0]))); 27 | 28 | printf("%d\n", majorityElement(num2, sizeof(num2)/sizeof(num2[0]))); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /src/27.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int removeElement(int A[], int n, int elem) { 4 | int i, j, len; 5 | len = n; 6 | i = 0, j = n - 1; 7 | while (i < len) { 8 | if (A[i] == elem) { 9 | int t = A[j]; 10 | A[j] = A[i]; 11 | A[i] = t; 12 | len--; 13 | j--; 14 | } 15 | else { 16 | i++; 17 | } 18 | } 19 | 20 | return len; 21 | } 22 | 23 | int main() { 24 | int A[] = { 3, 1, 2, 3, 3, 4, 5, 3, 6 }; 25 | int new_len = removeElement(A, sizeof(A) / sizeof(A[0]), 3); 26 | 27 | int i; 28 | for (i = 0; i < new_len; i++) { 29 | printf("%d ", A[i]); 30 | } 31 | printf("\n"); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/154.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int findMin(int *nums, int numsSize) { 5 | int l = 0; 6 | int r = numsSize - 1; 7 | while (l < r) { 8 | int m = l + (r - l) / 2; 9 | if (nums[l] > nums[m]) { /* right side is sorted */ 10 | r = m; 11 | } 12 | else if (nums[r] < nums[m]) { /* left side is sorted */ 13 | l = m + 1; 14 | } 15 | else { /* the sub-array is not rotated, 1 step to deal with dups */ 16 | r--; 17 | } 18 | } 19 | return nums[l]; 20 | } 21 | 22 | int main() { 23 | int nums[] = { 3, 3, 1, 3 }; 24 | 25 | assert(findMin(nums, sizeof(nums) / sizeof(nums[0])) == 1); 26 | 27 | printf("all tests passed!\n"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /src/268.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int missingNumber0(int* nums, int numsSize) { 5 | long long sum = 0; 6 | int i; 7 | for (i = 0; i < numsSize; i++) { 8 | sum += nums[i]; 9 | } 10 | 11 | long long prod = (numsSize + 1) * numsSize / 2; 12 | 13 | return prod - sum; 14 | } 15 | 16 | int missingNumber(int* nums, int numsSize) { 17 | int ans = 0; 18 | int i; 19 | for (i = 0; i < numsSize; i++) { 20 | ans ^= nums[i]; 21 | ans ^= i + 1; 22 | } 23 | 24 | return ans; 25 | } 26 | 27 | int main() { 28 | 29 | int a[] = {0, 1, 3}; 30 | assert(missingNumber(a, 3) == 2); 31 | int b[] = {1, 0}; 32 | assert(missingNumber(b, 2) == 2); 33 | 34 | printf("all tests passed!\n"); 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /src/89.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Return an array of size *returnSize. 6 | * Note: The returned array must be malloced, assume caller calls free(). 7 | */ 8 | int* grayCode(int n, int* returnSize) { 9 | *returnSize = 1 << n; 10 | int *gray = (int *)malloc(*returnSize * sizeof(int)); 11 | 12 | int i; 13 | for (i = 0; i < *returnSize; i++) { 14 | gray[i] = (i >> 1) ^ i; 15 | } 16 | 17 | return gray; 18 | } 19 | 20 | int main() { 21 | int n = 2; 22 | int returnSize = 0; 23 | 24 | int* ans = grayCode(n, &returnSize); 25 | int i; 26 | for (i = 0; i < returnSize; i++) { 27 | printf("%d ", ans[i]); 28 | } 29 | printf("\n"); 30 | 31 | free(ans); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/134.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) { 5 | if (gasSize != costSize) return -1; 6 | int i; 7 | int tank = 0, sum = 0; 8 | int ans = 0; 9 | for (i = 0; i < gasSize; i++) { 10 | sum += gas[i] - cost[i]; 11 | tank += gas[i] - cost[i]; 12 | if (sum < 0) { 13 | ans = i + 1; 14 | sum = 0; 15 | } 16 | } 17 | 18 | return tank >= 0 ? ans : -1; 19 | } 20 | 21 | int main() { 22 | int gas[] = { 1, 2 }; 23 | int cost[] = { 2, 1 }; 24 | 25 | assert(canCompleteCircuit(gas, sizeof(gas) / sizeof(gas[0]), 26 | cost, sizeof(cost) / sizeof(cost[0])) == 1); 27 | 28 | printf("all tests passed!\n"); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /src/168.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char *convertToTitle(int n) { 6 | char *ans = (char *)calloc(10, sizeof(char)); 7 | 8 | int i; 9 | i = 0; 10 | while (n > 0) { 11 | int t = n % 26; 12 | if (t == 0) { t = 26; ans[i] = 'Z'; } 13 | else { ans[i] = t + 'A' - 1; } 14 | n -= t; 15 | n /= 26; 16 | i++; 17 | } 18 | /* reverse string */ 19 | int j = strlen(ans) - 1; 20 | i = 0; 21 | while (i < j) { 22 | char t = ans[i]; 23 | ans[i] = ans[j]; 24 | ans[j] = t; 25 | i++; 26 | j--; 27 | } 28 | 29 | return ans; 30 | } 31 | 32 | int main() { 33 | int n = 26; 34 | printf("%s\n", convertToTitle(n)); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/263.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | bool isUgly(int num) { 6 | if (num <= 0) return false; 7 | 8 | while (num > 1) { 9 | bool flag = false; 10 | 11 | if (num % 2 == 0) { 12 | flag = true; 13 | num /= 2; 14 | } 15 | if (num % 3 == 0) { 16 | flag = true; 17 | num /= 3; 18 | } 19 | if (num % 5 == 0) { 20 | flag = true; 21 | num /= 5; 22 | } 23 | 24 | if (!flag) return false; 25 | } 26 | 27 | return true; 28 | } 29 | 30 | int main() { 31 | assert(isUgly(0) == false); 32 | assert(isUgly(1) == true); 33 | assert(isUgly(6) == true); 34 | assert(isUgly(14) == false); 35 | 36 | printf("all test passed.\n"); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /src/223.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define max(a,b) (((a) > (b)) ? (a) : (b)) 4 | #define min(a,b) (((a) < (b)) ? (a) : (b)) 5 | 6 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 7 | 8 | int s1 = (C - A) * (D - B); 9 | int s2 = (G - E) * (H - F); 10 | 11 | /* intersect square */ 12 | int s0 = 0; 13 | 14 | /* left-bottom */ 15 | int x1 = max(A, E); 16 | int y1 = max(B, F); 17 | 18 | /* right-top */ 19 | int x2 = min(C, G); 20 | int y2 = min(D, H); 21 | 22 | if ((x2 - x1 > 0) && (y2 - y1) > 0) 23 | { 24 | s0 = (x2 - x1) * (y2 - y1); 25 | } 26 | 27 | return s1 + s2 - s0; 28 | } 29 | 30 | int main() { 31 | 32 | /* should be 45 */ 33 | printf("%d\n", computeArea(-3, 0, 3, 4, 0, -1, 9, 2)); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/231.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /** 7 | * Power of 2 have exactly ONE of 1 in the binary, so we don't need a loop. 8 | * We just need to check if it equals to zero after doing ONE time of "n & (n - 1)". 9 | * And doing a logic AND operation to "n > 0" will exclude the negative number and 0. 10 | */ 11 | 12 | bool isPowerOfTwo(int n) { 13 | return (n > 0) && !(n & (n - 1)); 14 | } 15 | 16 | int main () { 17 | assert(isPowerOfTwo(INT32_MIN) == false); 18 | assert(isPowerOfTwo(-1024) == false); 19 | assert(isPowerOfTwo(0) == false); 20 | assert(isPowerOfTwo(1) == true); 21 | assert(isPowerOfTwo(1024) == true); 22 | assert(isPowerOfTwo(INT32_MAX) == false); 23 | 24 | printf("all test passed!\n"); 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/198.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int rob(int num[], int n) { 5 | if (n == 0) return 0; 6 | int *d = (int *)calloc(n + 2, sizeof(int)); 7 | int i; 8 | d[0] = d[1] = 0; /* dummy */ 9 | for (i = 2; i < n + 2; i++) { 10 | /* for each house, there are two choices: robbing and NOT robbing */ 11 | if (d[i - 2] + num[i - 2] > d[i - 1]) { /* rob */ 12 | d[i] = d[i - 2] + num[i - 2]; 13 | } 14 | else { /* don't rob */ 15 | d[i] = d[i - 1]; 16 | } 17 | } 18 | return d[n + 1]; 19 | } 20 | 21 | int main() { 22 | 23 | int num[] = { 1, 2, 3, 4, 5 }; 24 | /* should be 9 */ 25 | printf("%d\n", rob(num, sizeof(num) / sizeof(num[0]))); 26 | 27 | /* should be 0 */ 28 | printf("%d\n", rob(NULL, 0)); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /src/53.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | int maxSubArray(int A[], int n) { 5 | int i; 6 | int max, sum; 7 | max = A[0]; 8 | sum = 0; 9 | for (i = 0; i < n; i++) { 10 | sum += A[i]; 11 | if (sum > max) 12 | max = sum; 13 | if(sum < 0) 14 | sum = 0; 15 | } 16 | return max; 17 | } 18 | */ 19 | 20 | int maxSubArray(int A[], int n) { 21 | int i; 22 | int max, local; 23 | max = A[0]; 24 | local = 0; 25 | for (i = 0; i < n; i++) { 26 | local += A[i]; 27 | if (local < A[i]) 28 | local = A[i]; 29 | if (local > max) 30 | max = local; 31 | } 32 | return max; 33 | } 34 | 35 | 36 | int main() { 37 | int A[] = { -3, -2, 0, -1}; 38 | printf("%d\n", maxSubArray(A, 4)); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/122.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int maxProfit(int prices[], int n){ 4 | int i; 5 | int ret = 0; 6 | for (i = 1; i < n; i++) { 7 | int t = prices[i] - prices[i - 1]; 8 | if (t > 0) 9 | ret += t; 10 | } 11 | return ret; 12 | } 13 | 14 | /* 15 | int maxProfit(int prices[], int n){ 16 | int i; 17 | int ret = 0; 18 | int min = prices[0]; 19 | for (i = 1; i < n; i++) { 20 | if (prices[i] < prices[i - 1]) { 21 | ret += prices[i - 1] - min; 22 | min = prices[i]; 23 | } 24 | } 25 | if (prices[n - 1] > min) 26 | ret += prices[n - 1] - min; 27 | 28 | return ret; 29 | } 30 | */ 31 | 32 | int main() { 33 | int prices[] = {1, 2, 3, 2, 4}; 34 | printf("%d\n", maxProfit(prices, sizeof(prices)/sizeof(prices[0]))); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/152.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int maxProduct(int A[], int n) { 4 | int i; 5 | int min, max, ret; 6 | ret = max = min = A[0]; 7 | for (i = 1; i < n; i++) { 8 | int t_max = max; 9 | if (max * A[i] > A[i]) 10 | max *= A[i]; 11 | else 12 | max = A[i]; 13 | /* A[i] is negative*/ 14 | if (min * A[i] > max) 15 | max = min * A[i]; 16 | 17 | if (min * A[i] < A[i]) 18 | min *= A[i]; 19 | else 20 | min = A[i]; 21 | /* A[i] is negative*/ 22 | if (t_max * A[i] < min) 23 | min = t_max * A[i]; 24 | 25 | if (max > ret) 26 | ret = max; 27 | } 28 | return ret; 29 | } 30 | 31 | int main() { 32 | int A[] = {1, -2, 3, -2, -3}; 33 | printf("%d\n", maxProduct(A, 5)); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/233.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int countDigitOne(int n) { 5 | if (n <= 0) return 0; 6 | if (n >= 1 && n <= 9) return 1; 7 | 8 | int x = n; /* first digit of n */ 9 | int v = 1; /* first dight's weight */ 10 | while (x >= 10) { 11 | x /= 10; 12 | v *= 10; 13 | } 14 | 15 | if (x != 1) { 16 | return x * countDigitOne(v - 1) + countDigitOne(n % v) + v; 17 | } 18 | else { 19 | return countDigitOne(v - 1) + countDigitOne(n % v) + n % v + 1; 20 | } 21 | } 22 | 23 | int main() { 24 | assert(countDigitOne(-1) == 0); 25 | assert(countDigitOne(1) == 1); 26 | assert(countDigitOne(10) == 2); 27 | assert(countDigitOne(13) == 6); 28 | assert(countDigitOne(21) == 13); 29 | assert(countDigitOne(99) == 20); 30 | assert(countDigitOne(115) == 44); 31 | 32 | printf("all tests passed!\n"); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /src/66.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int* plusOne(int* digits, int digitsSize, int* returnSize) { 5 | int *ans = (int *)malloc((digitsSize + 1) * sizeof(int)); 6 | *returnSize = digitsSize; 7 | int i; 8 | int sum = 1; /* plus one */ 9 | for (i = digitsSize - 1; i >= 0; i--) { 10 | sum += digits[i]; 11 | ans[i + 1] = sum % 10; 12 | sum /= 10; 13 | } 14 | if (sum) { 15 | ans[0] = sum; 16 | *returnSize = *returnSize + 1; 17 | return ans; 18 | } 19 | else { 20 | return ans + 1; 21 | } 22 | } 23 | 24 | int main() { 25 | int A[] = { 9, 9, 9 }; 26 | int retSize = 0; 27 | int *ans = plusOne(A, sizeof(A) / sizeof(A[0]), &retSize); 28 | int i; 29 | for (i = 0; i < retSize; i++) { 30 | printf("%d ", ans[i]); 31 | } 32 | printf("\n"); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/278.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define BAD 3 // for testing 6 | 7 | // Forward declaration of isBadVersion API. 8 | bool isBadVersion(int version) { 9 | return (version >= BAD); 10 | } 11 | 12 | int firstBadVersion(int n) { 13 | if (n <= 1) return n; 14 | 15 | int low = 1; 16 | int high = n; 17 | int mid; 18 | while (low <= high) { 19 | mid = low + (high - low) / 2; 20 | if (isBadVersion(mid)) { 21 | high = mid - 1; 22 | } 23 | else { 24 | low = mid + 1; 25 | } 26 | } 27 | 28 | return low; 29 | } 30 | 31 | int main() { 32 | 33 | assert(firstBadVersion(3) == 3); 34 | assert(firstBadVersion(4) == 3); 35 | assert(firstBadVersion(5) == 3); 36 | assert(firstBadVersion(6) == 3); 37 | assert(firstBadVersion(7) == 3); 38 | assert(firstBadVersion(8) == 3); 39 | assert(firstBadVersion(9) == 3); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /src/162.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int findPeakElement(int* nums, int numsSize) { 5 | int left = 0, right = numsSize - 1, mid; 6 | while (left < right) { 7 | mid = left + (right - left) / 2; 8 | if ((mid == 0 && nums[mid] > nums[mid + 1]) 9 | || (mid == numsSize - 1 && nums[mid] > nums[mid - 1]) 10 | || (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1])) 11 | { 12 | return mid; 13 | } 14 | else if (nums[mid] < nums[mid + 1]) { 15 | left = mid + 1; 16 | } 17 | else if (nums[mid] < nums[mid - 1]) { 18 | right = mid - 1; 19 | } 20 | } 21 | 22 | return left; 23 | } 24 | 25 | int main() { 26 | int nums0[] = { 1, 2, 3, 1 }; 27 | int nums1[] = { 1, 2 }; 28 | assert(findPeakElement(nums0, sizeof(nums0) / sizeof(nums0[0])) == 2); 29 | assert(findPeakElement(nums1, sizeof(nums1) / sizeof(nums1[0])) == 1); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /src/237.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | void deleteNode(struct ListNode* node) { 10 | if (node == NULL || node->next == NULL) return; 11 | 12 | node->val = node->next->val; 13 | node->next = node->next->next; 14 | } 15 | 16 | void printList(struct ListNode* head) { 17 | while (head) { 18 | printf("%d->", head->val); 19 | head = head->next; 20 | } 21 | printf("N\n"); 22 | } 23 | 24 | int main() { 25 | 26 | struct ListNode *l1 = (struct ListNode *)calloc(3, sizeof(struct ListNode)); 27 | 28 | l1->val = 1; 29 | l1->next = l1 + 1; 30 | 31 | l1->next->val = 2; 32 | l1->next->next = l1 + 2; 33 | 34 | l1->next->next->val = 3; 35 | l1->next->next->next = NULL; 36 | 37 | printList(l1); 38 | 39 | /* delete 2 */ 40 | deleteNode(l1->next); 41 | 42 | printList(l1); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /src/242.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | bool isAnagram(char* s, char* t) { 8 | if (s == NULL || t == NULL) return false; 9 | 10 | int lens = strlen(s); 11 | int lent = strlen(t); 12 | if (lens != lent) return false; 13 | 14 | int flag[26] = { 0 }; 15 | int i; 16 | for (i = 0; i < lens; i++){ 17 | flag[s[i] - 'a']++; 18 | } 19 | 20 | for (i = 0; i < lent; i++) { 21 | flag[t[i] - 'a']--; 22 | } 23 | 24 | for (i = 0; i < 26; i++){ 25 | if (flag[i] != 0) return false; 26 | } 27 | 28 | return true; 29 | } 30 | 31 | int main() { 32 | 33 | assert(isAnagram("anagram", "nagaram") == true); 34 | assert(isAnagram("rat", "car") == false); 35 | assert(isAnagram("aba", "aab") == true); 36 | assert(isAnagram("aba", "ab") == false); 37 | 38 | printf("all tests passed!\n"); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/80.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int removeDuplicates(int* nums, int numsSize) { 4 | if (nums == NULL || numsSize == 0) return 0; 5 | 6 | int storeIndex = 0; 7 | int i = 0; 8 | while (i < numsSize) { 9 | int count = 1; 10 | while (i < numsSize - 1 && nums[i] == nums[i + 1]) { 11 | i++; 12 | count++; 13 | if (i >= numsSize) goto OUT; 14 | } 15 | if (count >= 2) { 16 | nums[storeIndex++] = nums[i]; 17 | nums[storeIndex++] = nums[i]; 18 | } 19 | else { 20 | nums[storeIndex++] = nums[i]; 21 | } 22 | i++; 23 | } 24 | OUT: 25 | return storeIndex; 26 | } 27 | 28 | int main() { 29 | int nums[] = { 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5 }; 30 | int new_len = removeDuplicates(nums, sizeof(nums) / sizeof(nums[0])); 31 | 32 | int i; 33 | for (i = 0; i < new_len; i++) { 34 | printf("%d ", nums[i]); 35 | } 36 | printf("\n"); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /src/33.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int search(int A[], int n, int target) { 4 | int l, r, m; 5 | l = 0; 6 | r = n - 1; 7 | while (l <= r) { 8 | m = (l + r) / 2; 9 | if (A[m] == target) return m; 10 | 11 | if (A[l] <= A[m]) { /* left half is sorted */ 12 | if (A[l] <= target && target < A[m]) { /* target in left half */ 13 | r = m - 1; 14 | } 15 | else { 16 | l = m + 1; 17 | } 18 | } 19 | else { /* right half is sorted */ 20 | if (A[m] < target && target <= A[r]) { /* target in right half */ 21 | l = m + 1; 22 | } 23 | else { 24 | r = m - 1; 25 | } 26 | } 27 | } 28 | return -1; 29 | } 30 | 31 | int main() { 32 | int num[] = { 1, 3, 5 }; 33 | /* should be 0 */ 34 | printf("%d\n", search(num, sizeof(num)/sizeof(num[0]), 1)); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/14.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char* longestCommonPrefix(char** strs, int strsSize) { 6 | char *ans; 7 | if (strsSize == 0) { 8 | ans = ""; 9 | return ans; 10 | } 11 | else { 12 | ans = malloc(strlen(strs[0])); 13 | strcpy(ans, strs[0]); 14 | } 15 | 16 | int i, j; 17 | for (j = 0; ans[j] != '\0'; j++) { 18 | for (i = 1; i < strsSize; i++) { 19 | if (strs[i][j] != ans[j]) { 20 | goto OUT; 21 | } 22 | } 23 | } 24 | 25 | OUT: 26 | ans[j] = '\0'; 27 | 28 | return ans; 29 | } 30 | 31 | int main() { 32 | char *strs[20] = { 33 | "abcde", 34 | "abceawsdffd", 35 | "abcsdas", 36 | "abcefwfdf", 37 | "abcd", 38 | "abc" 39 | }; 40 | 41 | char *s = longestCommonPrefix(strs, 6); 42 | printf("%s\n", s); 43 | 44 | s = longestCommonPrefix(NULL, 0); 45 | printf("%s\n", s); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /src/264.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int nthUglyNumber(int n) { 5 | if (n < 2) return 1; 6 | int *nums = (int *)malloc(n * sizeof(int)); 7 | nums[0] = 1; 8 | int i2 = 0, i3 = 0, i5 = 0; /* index of 2, 3, 5 respectively */ 9 | int k = 1; /* store index */ 10 | 11 | while (k < n) { 12 | int min = 0; 13 | if (nums[i2] * 2 <= nums[i3] * 3) { 14 | min = nums[i2] * 2; 15 | } 16 | else { 17 | min = nums[i3] * 3; 18 | } 19 | 20 | if (nums[i5] * 5 < min) { 21 | min = nums[i5] * 5; 22 | } 23 | 24 | nums[k++] = min; 25 | 26 | if (nums[i2] * 2 == min) i2++; 27 | if (nums[i3] * 3 == min) i3++; 28 | if (nums[i5] * 5 == min) i5++; 29 | } 30 | 31 | int ans = nums[n - 1]; 32 | free(nums); 33 | 34 | return ans; 35 | } 36 | 37 | int main() { 38 | 39 | int n = 10; 40 | int i; 41 | for (i = 1; i <= n; i++) { 42 | printf("%d ", nthUglyNumber(i)); 43 | } 44 | printf("\n"); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /src/129.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | void sumNumbersHelper(struct TreeNode* root, int* sum, int num) { 11 | if (root == NULL) return; 12 | 13 | num = num * 10 + root->val; 14 | if (root->left == NULL && root->right == NULL) { 15 | *sum += num; 16 | return; 17 | } 18 | 19 | sumNumbersHelper(root->left, sum, num); 20 | sumNumbersHelper(root->right, sum, num); 21 | } 22 | 23 | int sumNumbers(struct TreeNode* root) { 24 | if (root == NULL) return 0; 25 | 26 | int sum = 0, num = 0; 27 | sumNumbersHelper(root, &sum, num); 28 | 29 | return sum; 30 | } 31 | 32 | int main() { 33 | struct TreeNode* root = (struct TreeNode *)calloc(3, sizeof(struct TreeNode)); 34 | root->val = 1; 35 | root->left = root + 1; 36 | root->left->val = 2; 37 | root->right = root + 2; 38 | root->right->val = 3; 39 | 40 | /* should be 25 */ 41 | printf("%d\n", sumNumbers(root)); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /src/299.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define min(a,b) ((a)<(b)?(a):(b)) 7 | char* getHint(char* secret, char* guess) { 8 | char hashs[10] = { 0 }; 9 | char hashg[10] = { 0 }; 10 | int len = strlen(secret); 11 | int bulls = 0, cows = 0; 12 | int i; 13 | for (i = 0; i < len; i++) { 14 | if (secret[i] == guess[i]) { 15 | bulls++; 16 | } 17 | else { 18 | hashs[secret[i] - '0']++; 19 | hashg[guess[i] - '0']++; 20 | } 21 | } 22 | for (i = 0; i < 10; i++) { 23 | cows += min(hashs[i], hashg[i]); 24 | } 25 | 26 | char *hint = (char *)malloc(5); 27 | sprintf(hint, "%dA%dB", bulls, cows); 28 | hint[5] = '\0'; 29 | return hint; 30 | } 31 | 32 | int main() { 33 | assert(strcmp(getHint("1807", "7810"), "1A3B") == 0); 34 | assert(strcmp(getHint("1234", "0111"), "0A1B") == 0); 35 | assert(strcmp(getHint("1122", "2211"), "0A4B") == 0); 36 | 37 | printf("all tests passed!\n"); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /src/41.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int firstMissingPositive(int* nums, int numsSize) { 5 | int i; 6 | for (i = 0; i < numsSize; i++) { 7 | while (nums[i] > 0 && nums[i] < numsSize && nums[nums[i] - 1] != nums[i]) { 8 | int t = nums[i]; 9 | nums[i] = nums[t - 1]; 10 | nums[t - 1] = t; 11 | } 12 | } 13 | 14 | for (i = 0; i < numsSize; i++) { 15 | if (nums[i] != i + 1) 16 | break; 17 | } 18 | 19 | return i + 1; 20 | } 21 | 22 | int main() { 23 | 24 | int nums0[] = { 1, 2, 0 }; 25 | int nums1[] = { 3, 4, -1, 1 }; 26 | int nums2[] = { -1, 4, 2, 1, 9, 10 }; 27 | int nums3[] = { 1, 1 }; 28 | 29 | assert(firstMissingPositive(nums0, sizeof(nums0) / sizeof(nums0[0])) == 3); 30 | assert(firstMissingPositive(nums1, sizeof(nums1) / sizeof(nums1[0])) == 2); 31 | assert(firstMissingPositive(nums2, sizeof(nums2) / sizeof(nums2[0])) == 3); 32 | assert(firstMissingPositive(nums3, sizeof(nums3) / sizeof(nums3[0])) == 2); 33 | 34 | printf("all tests passed!\n"); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /src/91.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int numDecodings(char *s) { 7 | if (s == NULL) return 0; 8 | int len = strlen(s); 9 | if (len == 0) return 0; 10 | int *dp = (int *)malloc((len + 1) * sizeof(int)); 11 | int i; 12 | dp[0] = 1; 13 | dp[1] = (s[0] == '0') ? 0 : 1; 14 | for (i = 2; i < len + 1; i++) { 15 | dp[i] = (s[i - 1] == '0') ? 0 : dp[i - 1]; /*1 step*/ 16 | if (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6')) /*2 steps*/ 17 | dp[i] += dp[i - 2]; 18 | } 19 | int ans = dp[len]; 20 | free(dp); 21 | return ans; 22 | } 23 | 24 | int main() { 25 | char s0[] = "301"; 26 | char s1[] = ""; 27 | char s2[] = "0"; 28 | char s3[] = "01"; 29 | char s4[] = "112"; 30 | assert(numDecodings(s0) == 0); 31 | assert(numDecodings(s1) == 0); 32 | assert(numDecodings(s2) == 0); 33 | assert(numDecodings(s3) == 0); 34 | assert(numDecodings(s4) == 3); 35 | 36 | printf("all tests passed!\n"); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /src/204.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* 147 ms, a bit slow */ 6 | /* So weird, it's 39 ms now. Does the test mechanism change? */ 7 | /* I notice there is a line says "n is order in 1,000,000 to */ 8 | /* 5,000,000", but it's gone now. */ 9 | int countPrimes(int n) { 10 | bool *flag = (bool *)calloc(n + 1, sizeof(bool)); 11 | int *prime = (int *)calloc(n / 2, sizeof(int)); 12 | 13 | flag[0] = 1; /* dummy */ 14 | flag[1] = 1; /* dummy, 1 is not prime */ 15 | 16 | int i, j; 17 | int count = 0; 18 | for (i = 2; i < n; i++) { 19 | if (flag[i] == 0) { /* i is prime */ 20 | prime[count ++] = i; 21 | } 22 | for (j = 0; j < count && i * prime[j] < n; j++) { 23 | flag[i * prime[j]] = 1; 24 | if (i % prime[j] == 0) { /* important */ 25 | break; 26 | } 27 | } 28 | } 29 | return count; 30 | } 31 | 32 | int main() { 33 | 34 | /* 348513 */ 35 | printf("%d\n", countPrimes(5000000)); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /src/22.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector generateParenthesis(int n) { 10 | vector ans; 11 | string temp = ""; 12 | 13 | generateParenthesisHelper(ans, temp, n, n); 14 | 15 | return ans; 16 | } 17 | 18 | void generateParenthesisHelper(vector &ans, string temp, int left, int right) { 19 | if (left > right) return; 20 | 21 | if (left == 0 && right == 0) { 22 | ans.push_back(temp); 23 | return; 24 | } 25 | 26 | if (left > 0) 27 | generateParenthesisHelper(ans, temp + "(", left - 1, right); 28 | if (right > 0) 29 | generateParenthesisHelper(ans, temp + ")", left, right - 1); 30 | } 31 | }; 32 | 33 | int main() { 34 | int n = 4; 35 | Solution s; 36 | vector ans = s.generateParenthesis(n); 37 | 38 | for (int i = 0; i < ans.size(); i++) { 39 | cout << ans[i] << endl; 40 | } 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /src/77.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector > combine(int n, int k) { 10 | vector > ans; 11 | vector temp; 12 | 13 | combineHelper(1, n, k, temp, ans); 14 | 15 | return ans; 16 | } 17 | 18 | void combineHelper(int start, int end, int k, vector &temp, vector > &ans) { 19 | if (k == temp.size()) { 20 | ans.push_back(temp); 21 | return; 22 | } 23 | 24 | for (int i = start; i <= end; i++) { 25 | temp.push_back(i); 26 | combineHelper(i + 1, end, k, temp, ans); 27 | temp.pop_back(); 28 | } 29 | } 30 | }; 31 | 32 | int main() { 33 | int n = 4; 34 | int k = 2; 35 | Solution s; 36 | vector > ans = s.combine(n, k); 37 | 38 | for (int i = 0; i < ans.size(); i++) { 39 | for (int j = 0; j < ans[i].size(); j++) { 40 | printf("%d ", ans[i][j]); 41 | } 42 | printf("\n"); 43 | } 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /src/213.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define max(a,b) ((a)>(b)?(a):(b)) 6 | int robNoCircle(int num[], int n) { 7 | if (n == 0) return 0; 8 | int *dp = (int *)calloc(n + 2, sizeof(int)); 9 | int i; 10 | dp[0] = dp[1] = 0; /* dummy */ 11 | for (i = 2; i < n + 2; i++) { 12 | /* for each house, there are two choices: robbing and NOT robbing */ 13 | if (dp[i - 2] + num[i - 2] > dp[i - 1]) { /* rob */ 14 | dp[i] = dp[i - 2] + num[i - 2]; 15 | } 16 | else { /* don't rob */ 17 | dp[i] = dp[i - 1]; 18 | } 19 | } 20 | int ans = dp[n + 1]; 21 | free(dp); 22 | return ans; 23 | } 24 | 25 | int rob(int* nums, int numsSize) { 26 | if (nums == NULL || numsSize == 0) return 0; 27 | if (numsSize == 1) return nums[0]; 28 | return max(robNoCircle(nums, numsSize - 1), robNoCircle(nums + 1, numsSize - 1)); 29 | } 30 | 31 | int main() { 32 | int nums[] = { 1, 2, 3, 4, 5 }; 33 | 34 | assert(rob(nums, sizeof(nums) / sizeof(nums[0])) == 8); 35 | 36 | printf("all tests passed!\n"); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /src/115.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int numDistinct(char* s, char* t) { 7 | if (s == NULL || t == NULL) return 0; 8 | int n = strlen(s); 9 | int m = strlen(t); 10 | 11 | int (*dp)[n] = (int (*)[n])calloc(n * m, sizeof(int)); 12 | int i, j; 13 | 14 | dp[0][0] = (t[0] == s[0] ? 1 : 0); 15 | 16 | for (j = 1; j < n; j++) { 17 | dp[0][j] = dp[0][j - 1] + (t[0] == s[j] ? 1 : 0); 18 | } 19 | 20 | for (i = 1; i < m; i++) { 21 | dp[i][0] = 0; 22 | } 23 | 24 | for (i = 1; i < m; i++) { 25 | for (j = 1; j < n; j++) { 26 | if (t[i] == s[j]) { 27 | dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; 28 | } 29 | else { 30 | dp[i][j] = dp[i][j - 1]; 31 | } 32 | } 33 | } 34 | 35 | int ans = dp[m - 1][n - 1]; 36 | free(dp); 37 | 38 | return ans; 39 | } 40 | 41 | int main() { 42 | char s[] = "acaaca"; 43 | char t[] = "ca"; 44 | 45 | assert(numDistinct(s, t) == 4); 46 | 47 | printf("all tests passed!\n"); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /src/63.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int uniquePathsWithObstacles(int **obstacleGrid, int m, int n){ 5 | int (*p)[n] = (int (*)[n]) calloc(m * n, sizeof(int)); 6 | p[0][0] = 1; 7 | int i, j; 8 | for (i = 0; i < m; i++) { 9 | for (j = 0; j < n; j++) { 10 | if (obstacleGrid[i][j]) { 11 | p[i][j] = 0; 12 | } 13 | else { 14 | if (i > 0 && j == 0) 15 | p[i][j] = p[i - 1][j]; 16 | if (j > 0 && i == 0) 17 | p[i][j] = p[i][j - 1]; 18 | if (i > 0 && j > 0) 19 | p[i][j] = p[i][j - 1] + p[i - 1][j]; 20 | } 21 | } 22 | } 23 | 24 | return p[m - 1][n - 1]; 25 | } 26 | 27 | int main(){ 28 | int m, n, i; 29 | m = n = 3; 30 | int **obstacleGrid = (int **) calloc (m, sizeof(int *)); 31 | 32 | for (i = 0; i < m; i++) 33 | obstacleGrid[i] = (int *) calloc (n, sizeof(int)); 34 | 35 | obstacleGrid[1][1] = 1; 36 | 37 | printf("%d\n", uniquePathsWithObstacles(obstacleGrid, m, n)); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /src/292.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* Both two methods below suck, way too slow. 7 | 8 | bool canWinNim(int n) { 9 | if (n <= 0) return false; 10 | if (n >= 1 && n <= 3) return true; 11 | 12 | return !canWinNim(n - 1) | !canWinNim(n - 2) | !canWinNim(n - 3); 13 | } 14 | 15 | bool canWinNim(int n) { 16 | if (n <= 0) return false; 17 | if (n >= 1 && n <= 3) return true; 18 | 19 | int *dp = (int *)malloc((n + 1) * sizeof(int)); 20 | 21 | dp[0] = false; 22 | dp[1] = dp[2] = dp[3] = true; 23 | 24 | int i; 25 | for (i = 4; i <= n; i++) { 26 | dp[i] = !dp[i - 1] | !dp[i - 2] | !dp[i - 3]; 27 | } 28 | 29 | bool ans = dp[n]; 30 | free(dp); 31 | 32 | return ans; 33 | } 34 | */ 35 | 36 | bool canWinNim(int n) { 37 | return n % 4; 38 | } 39 | 40 | int main() { 41 | assert(canWinNim(1) == true); 42 | assert(canWinNim(4) == false); 43 | assert(canWinNim(5) == true); 44 | assert(canWinNim(7) == true); 45 | assert(canWinNim(34) == true); 46 | assert(canWinNim(1348820612) == false); 47 | 48 | printf("all tests passed!\n"); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /src/88.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void merge(int* nums1, int m, int* nums2, int n) { 4 | int i, j, k; 5 | i = m - 1; 6 | j = n - 1; 7 | k = m + n - 1; 8 | 9 | while (i >= 0 && j >= 0) { 10 | if (nums2[j] > nums1[i]) { 11 | nums1[k] = nums2[j]; 12 | j--; 13 | } 14 | else { 15 | nums1[k] = nums1[i]; 16 | i--; 17 | } 18 | k--; 19 | } 20 | 21 | while (j >= 0) { 22 | nums1[k] = nums2[j]; 23 | j--; 24 | k--; 25 | } 26 | } 27 | 28 | int main() { 29 | int nums1[] = { 4, 5, 6, 0, 0, 0 }; 30 | int nums2[] = { 1, 2, 3 }; 31 | int i; 32 | printf("nums1: "); 33 | 34 | for (i = 0; i < 3; i++) { 35 | printf("%d ", nums1[i]); 36 | } 37 | printf("\n"); 38 | 39 | printf("nums2: "); 40 | for (i = 0; i < 3; i++) { 41 | printf("%d ", nums2[i]); 42 | } 43 | printf("\n"); 44 | 45 | merge(nums1, 3, nums2, 3); 46 | 47 | printf("merged: "); 48 | for (i = 0; i < 6; i++) { 49 | printf("%d ", nums1[i]); 50 | } 51 | printf("\n"); 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /src/7.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // detect overflow 5 | int check(int a, int *p) { 6 | int64_t ret = (int64_t)a; 7 | *p = (int)ret; 8 | return ret >= INT32_MAX || ret <= INT32_MIN; 9 | } 10 | 11 | int check_add(int a, int b, int *p) { 12 | int64_t ret = (int64_t)a + (int64_t)b; 13 | *p = (int)ret; 14 | return ret >= INT32_MAX || ret <= INT32_MIN; 15 | } 16 | 17 | int check_mul(int a, int b, int *p) { 18 | int64_t ret = (int64_t)a * (int64_t)b; 19 | *p = (int)ret; 20 | return ret >= INT32_MAX || ret <= INT32_MIN; 21 | } 22 | 23 | int reverse(int x) { 24 | int ret = 0; 25 | int sign = 0; 26 | if (x < 0) { 27 | if (check(-x, &x)) return 0; 28 | sign = 1; 29 | } 30 | while (x >= 10) { 31 | if (check_add(ret, x % 10, &ret)) return 0; 32 | x /= 10; 33 | if (check_mul(ret, 10, &ret)) return 0; 34 | } 35 | 36 | if (check_add(ret, x, &ret)) return 0; 37 | 38 | if (sign) 39 | if (check(-ret, &ret)) return 0; 40 | return ret; 41 | } 42 | 43 | int main() { 44 | int x = -2147483648; 45 | printf("%d\n", reverse(x)); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /src/104.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | int maxDepth(struct TreeNode *root) { 11 | if (root == NULL) 12 | return 0; 13 | int l = maxDepth(root->left); 14 | int r = maxDepth(root->right); 15 | if (l > r) 16 | return l + 1; 17 | else 18 | return r + 1; 19 | } 20 | 21 | void printTreePreOrder(struct TreeNode *p) { 22 | if (p != NULL) { 23 | printf("%d", p->val); 24 | printTreePreOrder(p->left); 25 | printTreePreOrder(p->right); 26 | } 27 | else printf("#"); 28 | } 29 | 30 | int main() { 31 | struct TreeNode *t = (struct TreeNode *)calloc(4, sizeof(struct TreeNode)); 32 | struct TreeNode *p = t; 33 | p->val = 1; 34 | p->left = ++t; 35 | t->val = 2; 36 | t->left = t->right = NULL; 37 | p->right = ++t; 38 | t->val = 3; 39 | p->right->left = NULL; 40 | p->right->right = ++t; 41 | t->val = 4; 42 | t->left = t->right = NULL; 43 | printTreePreOrder(p); printf("\n"); 44 | 45 | printf("%d\n", maxDepth(p)); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /src/139.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool wordBreak(string s, unordered_set &dict) { 11 | int len = s.size(); 12 | vector possible(len, 0); 13 | 14 | for (int i = 0; i < len; i++) { 15 | if (dict.find(s.substr(0, i + 1)) != dict.end()) 16 | possible[i] = true; 17 | 18 | for (int j = 0; j < i; j++) { 19 | if (possible[j] && 20 | dict.find(s.substr(j + 1, i - j)) != dict.end()) { 21 | possible[i] = true; 22 | break; 23 | } 24 | } 25 | } 26 | /* 27 | for (vector::iterator it = possible.begin(); 28 | it != possible.end(); it++) 29 | cout << *it << endl; 30 | */ 31 | return possible[len - 1]; 32 | } 33 | }; 34 | 35 | int main() { 36 | Solution solution; 37 | string s = "leetcode"; 38 | unordered_set dict = { "leet", "code" }; 39 | cout << solution.wordBreak(s, dict) << endl; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/313.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int nthSuperUglyNumber(int n, int* primes, int primesSize) { 7 | if (n <= 0 || primesSize <= 0) return 1; 8 | 9 | int *index = (int *)calloc(primesSize, sizeof(int)); 10 | int *nums = (int *)calloc(n, sizeof(int)); 11 | 12 | nums[0] = 1; 13 | int storageIndex = 1; 14 | 15 | while (storageIndex < n) { 16 | int min = INT32_MAX; 17 | int i; 18 | for (i = 0; i < primesSize; i++) { 19 | if (nums[index[i]] * primes[i] < min) { 20 | min = nums[index[i]] * primes[i]; 21 | } 22 | } 23 | nums[storageIndex++] = min; 24 | for (i = 0; i < primesSize; i++) { 25 | if (nums[index[i]] * primes[i] == min) { 26 | index[i]++; 27 | } 28 | } 29 | } 30 | 31 | int ans = nums[n - 1]; 32 | 33 | free(index); 34 | free(nums); 35 | 36 | return ans; 37 | } 38 | 39 | int main() { 40 | int n = 3; 41 | int primes[] = { 2, 3, 5 }; 42 | 43 | assert(nthSuperUglyNumber(n, primes, sizeof(primes)/sizeof(primes[0])) == 3); 44 | 45 | printf("all tests passed!\n"); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /src/216.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector > combinationSum3(int k, int n) { 9 | vector > ans; 10 | vector temp; 11 | 12 | combinationSum3Helper(1, n, k, temp, ans); 13 | 14 | return ans; 15 | } 16 | 17 | void combinationSum3Helper(int start, int n, int k, vector &temp, vector > &ans) { 18 | if (k == temp.size() && n == 0) { 19 | ans.push_back(temp); 20 | return; 21 | } 22 | else if (temp.size() > k || n < 0) { 23 | return; 24 | } 25 | 26 | for (int i = start; i <= 9; i++) { 27 | temp.push_back(i); 28 | combinationSum3Helper(i + 1, n - i, k, temp, ans); 29 | temp.pop_back(); 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | int k = 3; 36 | int n = 7; 37 | Solution s; 38 | vector > ans = s.combinationSum3(k, n); 39 | 40 | for (int i = 0; i < ans.size(); i++) { 41 | for (int j = 0; j < ans[i].size(); j++) { 42 | printf("%d ", ans[i][j]); 43 | } 44 | printf("\n"); 45 | } 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /src/120.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print_tri(int **triangle, int numRows) { 5 | int i, j; 6 | for (i = 0; i < numRows; i++) { 7 | for (j = 0; j < numRows; j++) { 8 | printf("%d ", triangle[i][j]); 9 | } 10 | printf("\n"); 11 | } 12 | } 13 | 14 | int minimumTotal(int **triangle, int numRows) { 15 | int i, j; 16 | for (i = numRows - 1; i > 0; i--) { 17 | for (j = 0; j < i; j++) { 18 | if (triangle[i][j] < triangle[i][j + 1]) 19 | triangle[i-1][j] += triangle[i][j]; 20 | else 21 | triangle[i-1][j] += triangle[i][j + 1]; 22 | //print_tri(triangle, numRows); 23 | } 24 | } 25 | return triangle[0][0]; 26 | } 27 | 28 | int main() { 29 | int row = 3; 30 | int **triangle = (int **)calloc(row, sizeof(int *)); 31 | int i; 32 | for (i = 0; i < row; i++) { 33 | triangle[i] = (int *)calloc(row, sizeof(int)); 34 | } 35 | triangle[0][0] = -1; 36 | triangle[1][0] = 2; triangle[1][1] = 3; 37 | triangle[2][0] = 1; triangle[2][1] = -1; triangle[2][2] = -3; 38 | 39 | printf("%d\n", minimumTotal(triangle, row)); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/67.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char* addBinary(char* a, char* b) { 6 | int len_a = strlen(a); 7 | int len_b = strlen(b); 8 | int len = (len_a > len_b) ? (len_a) : (len_b); 9 | char *ans = (char *)malloc(len + 1); 10 | int i; 11 | int sum = 0; 12 | for (i = 0; i < len; i++) { 13 | if (i < len_a && i < len_b) { 14 | sum += (a[len_a - 1 - i] - '0') + (b[len_b - 1 - i] - '0'); 15 | } 16 | else if (i < len_a) { 17 | sum += a[len_a - 1 - i] - '0'; 18 | } 19 | else if (i < len_b) { 20 | sum += b[len_b - 1 - i] - '0'; 21 | } 22 | ans[len - i] = sum % 2 + '0'; 23 | sum /= 2; 24 | } 25 | 26 | ans[len + 1] = '\0'; 27 | 28 | if (sum) { 29 | ans[0] = sum + '0'; 30 | return ans; 31 | } 32 | else { 33 | return ans + 1; 34 | } 35 | } 36 | 37 | int main() { 38 | /* should be 100 */ 39 | printf("%s\n", addBinary("11", "1")); 40 | 41 | /* should be 0 */ 42 | printf("%s\n", addBinary("0", "0")); 43 | 44 | /* should be 11000 */ 45 | printf("%s\n", addBinary("1011", "1101")); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /src/205.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | bool isIsomorphic(char* s, char* t) { 7 | int len = strlen(s); /* same length */ 8 | 9 | char hashs[128] = { 0 }; /* for ascii code */ 10 | char hasht[128] = { 0 }; 11 | int i; 12 | for (i = 0; i < len; i++) { 13 | int x = s[i]; 14 | if (hashs[x] == 0) { 15 | hashs[x] = t[i]; 16 | } 17 | else { 18 | if (hashs[x] != t[i]) { 19 | return false; 20 | } 21 | } 22 | 23 | int y = t[i]; 24 | if (hasht[y] == 0) { 25 | hasht[y] = s[i]; 26 | } 27 | else { 28 | if (hasht[y] != s[i]) { 29 | return false; 30 | } 31 | } 32 | } 33 | 34 | return true; 35 | } 36 | 37 | int main() { 38 | assert(isIsomorphic("egg", "add") == true); 39 | 40 | assert(isIsomorphic("foo", "bar") == false); 41 | 42 | assert(isIsomorphic("paper", "title") == true); 43 | 44 | assert(isIsomorphic("bar", "foo") == false); 45 | 46 | assert(isIsomorphic("13", "42") == true); 47 | 48 | printf("success!\n"); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /src/52.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | bool isValid(int *columns, int row) { 6 | int i; 7 | for (i = 0; i < row; i++) { 8 | if (columns[i] == columns[row] 9 | || (columns[i] - columns[row] == i - row) 10 | || (columns[i] - columns[row] == row - i)) { 11 | return false; 12 | } 13 | } 14 | return true; 15 | } 16 | 17 | void placeQueens(int *count, int *columns, int row, int n) { 18 | int j; /* column */ 19 | if (row == n) { /* found one solution */ 20 | (*count) ++; 21 | return; 22 | } 23 | for (j = 0; j < n; j++) { 24 | /* try to place a queen */ 25 | columns[row] = j; 26 | if (isValid(columns, row)) { 27 | /* place another queen */ 28 | placeQueens(count, columns, row + 1, n); 29 | } 30 | } 31 | } 32 | 33 | int totalNQueens(int n) { 34 | int count = 0; 35 | int *columns = (int *)calloc(n, sizeof(int)); 36 | placeQueens(&count, columns, 0, n); 37 | return count; 38 | } 39 | 40 | int main() { 41 | printf("%d\n", totalNQueens(4)); /* should be 2 */ 42 | printf("%d\n", totalNQueens(8)); /* should be 92 */ 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /src/93.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector restoreIpAddresses(string s) { 10 | vector temp; 11 | vector ans; 12 | 13 | dfs(s, temp, ans); 14 | 15 | return ans; 16 | } 17 | 18 | void dfs(string s, vector &temp, vector &ans) { 19 | if (temp.size() == 4 && s.length() == 0) { 20 | ans.push_back(temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3]); 21 | return; 22 | } 23 | else if (temp.size() >= 4) { 24 | return; 25 | } 26 | 27 | for(int i = 1; i <= 3 && i <= s.length(); i++) { 28 | string t = s.substr(0, i); 29 | if (t.length() > 1 && t[0] == '0') break; 30 | if (stoi(t) > 255) break; 31 | temp.push_back(t); 32 | dfs(s.substr(i, s.length() - i), temp, ans); 33 | temp.pop_back(); 34 | } 35 | } 36 | }; 37 | 38 | int main() { 39 | string str = "010010"; 40 | Solution s; 41 | vector ret = s.restoreIpAddresses(str); 42 | 43 | for (int i = 0; i < ret.size(); i++) { 44 | cout << ret[i] << endl; 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /src/43.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char* multiply(char* num1, char* num2) { 6 | if (num1 == NULL || num2 == NULL) return NULL; 7 | 8 | int len1 = strlen(num1); 9 | int len2 = strlen(num2); 10 | 11 | int *prod = (int *)calloc(len1 + len2 + 1, sizeof(int)); 12 | int i, j, k = 0; 13 | for (i = len1 - 1; i >= 0; i--) { 14 | k = len1 - 1 - i; 15 | for (j = len2 - 1; j >= 0; j--) { 16 | prod[k++] += (num1[i] - '0') * (num2[j] - '0'); 17 | } 18 | } 19 | 20 | k++; /* the last carry digit */ 21 | 22 | /* carry all */ 23 | int c = 0; 24 | for (i = 0; i < k - 1; i++) { 25 | c = prod[i] / 10; 26 | prod[i] = prod[i] % 10; 27 | prod[i + 1] += c; 28 | } 29 | 30 | /* remove lead zeros */ 31 | while (k > 1 && prod[k - 1] == 0) k--; 32 | 33 | char *ans = (char *)calloc(k + 1, sizeof(char)); 34 | /* reverse */ 35 | for (i = 0; i < k; i++) { 36 | ans[i] = prod[k - 1 - i] + '0'; 37 | } 38 | ans[k] = '\0'; 39 | 40 | free(prod); 41 | 42 | return ans; 43 | } 44 | 45 | int main() { 46 | char num1[] = "123456789"; 47 | char num2[] = "987654321"; 48 | 49 | printf("%s\n", multiply(num1, num2)); 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /src/8.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int myAtoi(char *str) { 5 | int64_t ret = 0; 6 | int sign = 1; 7 | char *p = str; 8 | /* ignore white spaces */ 9 | while (*p == ' ') p++; 10 | 11 | if (*p == '-') { 12 | sign = -1; 13 | p++; 14 | } 15 | else if (*p == '+') { 16 | sign = 1; 17 | p++; 18 | } 19 | 20 | while (*p >= '0' && *p <= '9') { 21 | ret = ret * 10 + (*p - '0'); 22 | if (ret - 1 > INT32_MAX) ret = (int64_t)INT32_MAX + 1; 23 | //printf("%ld\n", ret); 24 | p++; 25 | } 26 | 27 | if (sign == -1) ret = -ret; 28 | if (ret > INT32_MAX) ret = INT32_MAX; 29 | if (ret < INT32_MIN) ret = INT32_MIN; 30 | 31 | return (int)ret; 32 | } 33 | 34 | int main() { 35 | char *s[12]; 36 | s[0] = " 123 "; 37 | s[1] = "123.4"; 38 | s[2] = "-1234"; 39 | s[3] = "2147483646"; 40 | s[4] = "2147483647"; 41 | s[5] = "2147483648"; 42 | s[6] = "-2147483647"; 43 | s[7] = "-2147483648"; 44 | s[8] = "-2147483649"; 45 | s[9] = "-1"; 46 | s[10] = "+-2"; 47 | s[11] = "9223372036854775809"; 48 | 49 | int i; 50 | for (i = 0; i < 12; i++) 51 | printf("%d\n", myAtoi(s[i])); 52 | 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /src/260.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Return an array of size *returnSize. 6 | * Note: The returned array must be malloced, assume caller calls free(). 7 | */ 8 | int* singleNumber(int* nums, int numsSize, int* returnSize) { 9 | if (nums == NULL || returnSize == NULL) return 0; 10 | *returnSize = 2; 11 | int *ans = (int *)calloc(*returnSize, sizeof(int)); 12 | 13 | int x = 0; 14 | int i; 15 | for (i = 0; i < numsSize; i++) { 16 | x ^= nums[i]; 17 | } 18 | 19 | /* get first 1 in xor */ 20 | int k = 0; 21 | while (((x >> k) & 1) == 0) k++; 22 | 23 | /* group numbers in two by k-bit */ 24 | int a = 0, b = 0; 25 | for (i = 0; i < numsSize; i++) { 26 | if (nums[i] & (1 << k)) { 27 | a ^= nums[i]; 28 | } 29 | else { 30 | b ^= nums[i]; 31 | } 32 | } 33 | 34 | ans[0] = a; 35 | ans[1] = b; 36 | 37 | return ans; 38 | } 39 | 40 | int main () { 41 | int nums[] = {1, 2, 1, 3, 2, 5}; 42 | int returnSize = 0; 43 | 44 | int *ans = singleNumber(nums, sizeof(nums) / sizeof(nums[0]), &returnSize); 45 | 46 | int i; 47 | for (i = 0; i < returnSize; i++) { 48 | printf("%d ", ans[i]); 49 | } 50 | printf("\n"); 51 | 52 | free(ans); 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /src/118.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Return an array of arrays of size *returnSize. 6 | * The sizes of the arrays are returned as *columnSizes array. 7 | * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). 8 | */ 9 | int** generate(int numRows, int** columnSizes, int* returnSize) { 10 | *returnSize = numRows; 11 | int **ans = (int **)calloc(*returnSize, sizeof(int *)); 12 | (*columnSizes) = (int *)calloc(*returnSize, sizeof(int)); 13 | 14 | int i, j; 15 | 16 | for (i = 0; i < *returnSize; i++) { 17 | (*columnSizes)[i] = i + 1; 18 | ans[i] = (int *)calloc((*columnSizes)[i], sizeof(int)); 19 | ans[i][0] = 1; 20 | for (j = 1; j < i; j++) { 21 | ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]; 22 | } 23 | ans[i][i] = 1; 24 | } 25 | 26 | return ans; 27 | } 28 | 29 | int main() { 30 | 31 | int returnSize = 0; 32 | int *columnSizes = NULL; 33 | int **ret = generate(5, &columnSizes, &returnSize); 34 | 35 | int i, j; 36 | for(i = 0; i < returnSize; i++) { 37 | for (j = 0; j < columnSizes[i]; j++) { 38 | printf("%d ", ret[i][j]); 39 | } 40 | printf("\n"); 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /src/238.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Return an array of size *returnSize. 6 | * Note: The returned array must be malloced, assume caller calls free(). 7 | */ 8 | 9 | int* productExceptSelf(int* nums, int numsSize, int* returnSize) { 10 | if (nums == NULL || numsSize == 0) return NULL; 11 | 12 | int *output = (int *)malloc(numsSize * sizeof(int)); 13 | *returnSize = numsSize; 14 | 15 | int i; 16 | for (i = 0; i < numsSize; i++) { /* initialize all outputs to 1 */ 17 | output[i] = 1; 18 | } 19 | 20 | int prodLeft = 1; /* product from left */ 21 | for (i = 1; i < numsSize; i++) { 22 | prodLeft *= nums[i - 1]; 23 | output[i] *= prodLeft; 24 | } 25 | 26 | int prodRight = 1; /* product from right */ 27 | for (i = numsSize - 2; i >= 0; i--){ 28 | prodRight *= nums[i + 1]; 29 | output[i] *= prodRight; 30 | } 31 | 32 | return output; 33 | } 34 | 35 | int main() { 36 | int nums[] = { 1, 2, 3, 4 }; 37 | int returnSize = 0; 38 | 39 | int* output = productExceptSelf(nums, sizeof(nums)/sizeof(nums[0]), &returnSize); 40 | int i; 41 | for (i = 0; i < returnSize; i++) { 42 | printf("%d ", output[i]); 43 | } 44 | printf("\n"); 45 | 46 | free(output); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /src/116.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeLinkNode { 5 | int val; 6 | struct TreeLinkNode *left, *right, *next; 7 | }; 8 | 9 | void connectHelper(struct TreeLinkNode *node, struct TreeLinkNode *sibling) { 10 | if (node == NULL) return; 11 | if (!node->left || !node->right) return; 12 | 13 | /* node have two children */ 14 | node->left->next = node->right; 15 | node->right->next = (sibling == NULL) ? NULL : sibling->left; 16 | 17 | connectHelper(node->left, node->right); 18 | connectHelper(node->right, node->right->next); 19 | } 20 | 21 | void connect(struct TreeLinkNode *root) { 22 | if (root == NULL) return; 23 | 24 | root->next = NULL; 25 | connectHelper(root, NULL); 26 | } 27 | 28 | int main() { 29 | struct TreeLinkNode *root = (struct TreeLinkNode *)calloc(7, sizeof(struct TreeLinkNode)); 30 | root->val = 1; 31 | root->left = root + 1; 32 | root->left->val = 2; 33 | root->right = root + 2; 34 | root->right->val = 3; 35 | 36 | root->left->left = root + 3; 37 | root->left->left->val = 4; 38 | root->left->right = root + 4; 39 | root->left->right->val = 5; 40 | 41 | root->right->left = root + 5; 42 | root->right->left->val = 6; 43 | root->right->right = root + 6; 44 | root->right->right->val = 7; 45 | 46 | connect(root); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /src/142.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode *detectCycle(struct ListNode *head) { 10 | if (head == NULL) return NULL; 11 | 12 | struct ListNode *fast = head, *slow = head; 13 | while (fast && fast->next) { 14 | slow = slow->next; 15 | fast = fast->next->next; 16 | if (fast == slow) break; 17 | } 18 | 19 | if (fast == NULL || fast->next == NULL) return NULL; 20 | 21 | slow = head; 22 | while (slow != fast) { 23 | slow = slow->next; 24 | fast = fast->next; 25 | } 26 | 27 | return slow; 28 | } 29 | 30 | int main() { 31 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 32 | struct ListNode *p = l1; 33 | p->val = 1; 34 | p->next = l1 + 1; 35 | p = p->next; 36 | 37 | p->val = 2; 38 | p->next = l1 + 2; 39 | p = p->next; 40 | 41 | p->val = 3; 42 | p->next = l1 + 3; 43 | p = p->next; 44 | 45 | p->val = 4; 46 | p->next = l1 + 4; 47 | p = p->next; 48 | 49 | p->val = 5; 50 | p->next = l1 + 2; /* cycle to 3 */ 51 | 52 | struct ListNode *node = detectCycle(l1); 53 | 54 | if (node) { 55 | printf("%d\n", node->val); 56 | } 57 | else { 58 | printf("NIL\n"); 59 | } 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /src/144.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct TreeNode { 8 | int val; 9 | TreeNode *left; 10 | TreeNode *right; 11 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 12 | }; 13 | 14 | class Solution { 15 | public: 16 | vector preorderTraversal(TreeNode *root) { 17 | vector ret; 18 | if (!root) return ret; 19 | 20 | stack s; 21 | s.push(root); 22 | 23 | while (!s.empty()) { 24 | TreeNode *p = s.top(); 25 | s.pop(); 26 | 27 | if (p) { 28 | ret.push_back(p->val); 29 | s.push(p->right); 30 | s.push(p->left); 31 | } 32 | } 33 | return ret; 34 | } 35 | }; 36 | 37 | int main() { 38 | TreeNode *root = new TreeNode(4); 39 | TreeNode *p = root; 40 | 41 | p->left = new TreeNode(2); 42 | p->right = new TreeNode(5); 43 | p = p->left; 44 | p->left = new TreeNode(1); 45 | p->right = new TreeNode(3); 46 | 47 | Solution s; 48 | vector ret = s.preorderTraversal(root); 49 | 50 | // should be 42135 51 | for (unsigned int i = 0; i < ret.size(); i++) { 52 | cout << ret[i]; 53 | } 54 | cout << endl; 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /src/64.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int minPathSum(int **grid, int nRows, int nCols) { 5 | int i, j; 6 | for (i = 0; i < nRows; i++) { 7 | for (j = 0; j < nCols; j++) { 8 | if (i > 0 && j == 0) 9 | grid[i][j] += grid[i - 1][j]; 10 | if (j > 0 && i == 0) 11 | grid[i][j] += grid[i][j - 1]; 12 | if (i > 0 && j > 0) { 13 | if (grid[i][j - 1] < grid[i - 1][j]) 14 | grid[i][j] += grid[i][j - 1]; 15 | else 16 | grid[i][j] += grid[i - 1][j]; 17 | } 18 | } 19 | } 20 | /* 21 | for (i = 0; i < nRows; i++) { 22 | for (j = 0; j < nCols; j++) { 23 | printf("%d ", grid[i][j]); 24 | } 25 | printf("\n"); 26 | } 27 | */ 28 | return grid[nRows - 1][nCols - 1]; 29 | } 30 | 31 | int main() { 32 | int m, n, i; 33 | m = n = 3; 34 | int **grid = (int **) calloc (m, sizeof(int *)); 35 | 36 | for (i = 0; i < m; i++) 37 | grid[i] = (int *) calloc (n, sizeof(int)); 38 | 39 | grid[0][0] = 1; grid[0][1] = 2; grid[0][2] = 3; 40 | grid[1][0] = 1; grid[1][1] = 2; grid[1][2] = 3; 41 | grid[2][0] = 1; grid[2][1] = 2; grid[2][2] = 3; 42 | 43 | printf("%d\n", minPathSum(grid, m, n)); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /src/257.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct TreeNode { 9 | int val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | }; 14 | 15 | class Solution { 16 | public: 17 | vector binaryTreePaths(TreeNode *root) { 18 | string path = ""; 19 | vector ans; 20 | 21 | dfs(root, ans, path); 22 | 23 | return ans; 24 | } 25 | 26 | void dfs(TreeNode *root, vector &ans, string path) { 27 | if (root == NULL) { 28 | return; 29 | } 30 | 31 | path += to_string(root->val); 32 | 33 | if (root->left == NULL && root->right == NULL) { 34 | ans.push_back(path); 35 | return; 36 | } 37 | 38 | path += "->"; 39 | 40 | dfs(root->left, ans, path); 41 | dfs(root->right, ans, path); 42 | } 43 | }; 44 | 45 | int main() { 46 | TreeNode *r = new TreeNode(1); 47 | r->left = new TreeNode(2); 48 | r->right = new TreeNode(3); 49 | r->left->left = NULL; 50 | r->left->right = new TreeNode(5); 51 | 52 | Solution s; 53 | vector paths = s.binaryTreePaths(r); 54 | 55 | for (int i = 0; i < paths.size(); i++) { 56 | cout << paths[i] << endl; 57 | } 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /src/141.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct ListNode { 6 | int val; 7 | struct ListNode *next; 8 | }; 9 | 10 | bool hasCycle(struct ListNode *head) { 11 | if (head == NULL) return false; 12 | struct ListNode *fast, *slow; 13 | fast = slow = head; 14 | while (fast && slow) { 15 | if (fast) fast = fast->next; 16 | if (fast) fast = fast->next; 17 | 18 | if (slow) slow = slow->next; 19 | 20 | if (fast == slow && slow != NULL) return true; 21 | } 22 | 23 | return false; 24 | } 25 | 26 | int main() { 27 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 28 | struct ListNode *p = l1; 29 | p->val = 1; 30 | p->next = l1 + 1; 31 | p = p->next; 32 | 33 | p->val = 2; 34 | p->next = l1 + 2; 35 | p = p->next; 36 | 37 | p->val = 3; 38 | p->next = l1 + 3; 39 | p = p->next; 40 | 41 | p->val = 4; 42 | p->next = l1 + 4; 43 | p = p->next; 44 | 45 | p->val = 5; 46 | p->next = NULL; /* no cycle */ 47 | 48 | printf("%d\n", hasCycle(l1)); 49 | 50 | /* no cycle */ 51 | printf("%d\n", hasCycle(l1 + 4)); 52 | 53 | p->next = l1 + 2; /* cycle */ 54 | printf("%d\n", hasCycle(l1)); 55 | 56 | /* no cycle */ 57 | printf("%d\n", hasCycle(NULL)); 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /src/5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string longestPalindrome(string s) { 10 | int n = s.length(); 11 | int start = 0, maxLen = 1; // important, cos a single letter is palindrome 12 | int i, j, k ; 13 | for (i = 0; i < n; i++) { 14 | j = i, k = i + 1; //even length 15 | while (j >= 0 && k < n) { 16 | if (s[j] != s[k]) break; 17 | if (k - j + 1 > maxLen) { 18 | start = j; 19 | maxLen = k - j + 1; 20 | } 21 | j--; 22 | k++; 23 | } 24 | j = i - 1, k = i + 1; // odd length 25 | while(j >= 0 && k <= n - 1) { 26 | if (s[j] != s[k]) break; 27 | if (k - j + 1 > maxLen) { 28 | start = j; 29 | maxLen = k - j + 1; 30 | } 31 | j--; 32 | k++; 33 | } 34 | } 35 | return s.substr(start, maxLen); 36 | } 37 | }; 38 | 39 | int main() { 40 | string str0 = "aabac"; 41 | string str1 = "a"; 42 | Solution s; 43 | 44 | assert(s.longestPalindrome(str0) == "aba"); 45 | assert(s.longestPalindrome(str1) == "a"); 46 | 47 | printf("all tests passed!\n"); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /src/34.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector searchRange(vector& nums, int target) { 9 | vector ans(2); 10 | int n = nums.size(); 11 | int low = 0; 12 | int high = n - 1; 13 | int mid; 14 | bool found = false; 15 | while (low <= high) { 16 | mid = low + (high - low) / 2; 17 | if (nums[mid] == target) { 18 | found = true; 19 | break; 20 | } 21 | else if (nums[mid] < target) { 22 | low = mid + 1; 23 | } 24 | else { 25 | high = mid - 1; 26 | } 27 | } 28 | 29 | if (found) { 30 | low = high = mid; 31 | while (low >= 0 && nums[low] == target) low--; 32 | while (high <= n - 1 && nums[high] == target) high++; 33 | 34 | ans[0] = low + 1; 35 | ans[1] = high - 1; 36 | } 37 | else { 38 | ans[0] = ans[1] = -1; 39 | } 40 | 41 | return ans; 42 | } 43 | }; 44 | 45 | int main () { 46 | vector nums = {5, 7, 7, 8, 8, 10}; 47 | int target = 8; 48 | Solution s; 49 | 50 | vector ans = s.searchRange(nums, target); 51 | 52 | for (int i = 0; i < ans.size(); i++) { 53 | printf("%d ", ans[i]); 54 | } 55 | printf("\n"); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/279.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define EPSILON 1e-8 8 | 9 | /* a bit slow, 144 ms */ 10 | int numSquares(int n) { 11 | if (n <= 0) return 0; 12 | if (n == 1) return 1; 13 | 14 | int *squares = (int *)calloc(n, sizeof(int)); 15 | int *dp = (int *)calloc(n + 1, sizeof(int)); 16 | 17 | int k; 18 | int storeIndex = 0; 19 | for (k = 1; k <= n; k++) { 20 | double root = sqrt(k); 21 | if (fabs(root - (int)root) < EPSILON) { /* check if k is perfect square */ 22 | squares[storeIndex++] = k; 23 | } 24 | } 25 | 26 | int i, j; 27 | dp[0] = 0; /* dummy */ 28 | dp[1] = 1; 29 | for (i = 2; i <= n; i++) { 30 | int min = INT32_MAX; 31 | for (j = 0; squares[j] <= i && j < storeIndex; j++) { 32 | if (dp[i - squares[j]] + 1 < min) { 33 | min = dp[i - squares[j]] + 1; 34 | } 35 | } 36 | dp[i] = min; 37 | } 38 | 39 | int ans = dp[n]; 40 | free(squares); 41 | free(dp); 42 | 43 | return ans; 44 | } 45 | 46 | int main() { 47 | assert(numSquares(1) == 1); 48 | assert(numSquares(2) == 2); 49 | assert(numSquares(3) == 3); 50 | assert(numSquares(4) == 1); 51 | assert(numSquares(5) == 2); 52 | assert(numSquares(12) == 3); 53 | assert(numSquares(13) == 2); 54 | 55 | printf("all tests passed!\n"); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/189.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void rotate(int nums[], int n, int k) { 4 | int i, j, c; 5 | i = j = 0; 6 | int pre = nums[i]; 7 | int t; 8 | for(c = 0; c < n; c++) { 9 | i = (i + k) % n; 10 | t = nums[i]; 11 | nums[i] = pre; 12 | pre = t; 13 | if (i == j) { 14 | i = ++j; 15 | pre = nums[i]; 16 | } 17 | } 18 | } 19 | 20 | /* 21 | Cyclic group generator to do matrix transpose. 22 | use a 1-dimension array to reprents m*n matrix. 23 | the result is an n*m matrix. 24 | */ 25 | 26 | void transpose(int *matrix, int m, int n) { 27 | int i, j, c; 28 | i = j = 0; 29 | int pre = matrix[0]; 30 | int t; 31 | for (c = 0; c < m * n - 1; c++) { /* pay attention it's m*n-1 */ 32 | i = (i % n) * m + (i / n); 33 | t = matrix[i]; 34 | matrix[i] = pre; 35 | pre = t; 36 | if (i == j) { 37 | i = ++j; 38 | pre = matrix[i]; 39 | } 40 | } 41 | } 42 | 43 | void print(int nums[], int n) { 44 | int i; 45 | for (i = 0; i < n; i++) { 46 | printf("%d ", nums[i]); 47 | } 48 | printf("\n"); 49 | } 50 | 51 | int main() 52 | { 53 | int a[7] = {1, 2, 3, 4, 5, 6, 7}; 54 | int n = 7; 55 | int k = 4; 56 | 57 | rotate(a, n, k); 58 | print(a, n); 59 | 60 | int b[6] = {1, 2, 3, 4, 5, 6}; 61 | n = 6; 62 | k = 3; 63 | 64 | rotate(b, n, k); 65 | print(b, n); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /src/83.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* deleteDuplicates(struct ListNode* head) { 10 | if (head == NULL) return head; 11 | 12 | struct ListNode *pre = head; 13 | struct ListNode *p = head->next; 14 | 15 | while (p) { 16 | if (pre->val == p->val) { 17 | p = p->next; 18 | pre->next = p; 19 | } 20 | else { 21 | pre = p; 22 | p = p->next; 23 | } 24 | } 25 | 26 | return head; 27 | } 28 | 29 | int main() { 30 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 31 | struct ListNode *p = NULL; 32 | 33 | p = l1; 34 | p->val = 1; 35 | p->next = l1 + 1; 36 | p = p->next; 37 | 38 | p->val = 1; 39 | p->next = l1 + 2; 40 | p = p->next; 41 | 42 | p->val = 3; 43 | p->next = l1 + 3; 44 | p = p->next; 45 | 46 | p->val = 3; 47 | p->next = l1 + 4; 48 | p = p->next; 49 | 50 | p->val = 3; 51 | p->next = NULL; 52 | 53 | p = l1; 54 | while (p) { 55 | printf("%d ", p->val); 56 | p = p->next; 57 | } 58 | printf("\n"); 59 | 60 | p = deleteDuplicates(l1); 61 | 62 | while (p) { 63 | printf("%d ", p->val); 64 | p = p->next; 65 | } 66 | printf("\n"); 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /src/241.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector diffWaysToCompute(string input) { 9 | vector result; 10 | for (int k = 0; k < input.length(); k++) { 11 | if (input[k] == '*' || input[k] == '-' || input[k] == '+') { 12 | vector a = diffWaysToCompute(input.substr(0, k)); 13 | vector b = diffWaysToCompute(input.substr(k + 1)); 14 | for (int i = 0; i < a.size(); i++) { 15 | for (int j = 0; j < b.size(); j++) { 16 | if (input[k] == '+') { 17 | result.push_back(a[i] + b[j]); 18 | } 19 | else if (input[k] == '-') { 20 | result.push_back(a[i] - b[j]); 21 | } 22 | else { 23 | result.push_back(a[i] * b[j]); 24 | } 25 | } 26 | } 27 | 28 | } 29 | } 30 | if (result.size() == 0) { 31 | result.push_back(stoi(input)); 32 | } 33 | return result; 34 | } 35 | }; 36 | 37 | int main() { 38 | 39 | Solution s; 40 | vector ans = s.diffWaysToCompute("2*3-4*5"); 41 | 42 | for (int i = 0; i < ans.size(); i++) { 43 | printf("%d ", ans[i]); 44 | } 45 | printf("\n"); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /src/112.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct TreeNode { 6 | int val; 7 | struct TreeNode *left; 8 | struct TreeNode *right; 9 | }; 10 | 11 | bool hasPathSum(struct TreeNode *root, int sum) { 12 | if (root == NULL) { 13 | return false; 14 | } 15 | int remain = sum - root->val; 16 | 17 | if (root->left == NULL && root->right == NULL && remain == 0) { /* leaf */ 18 | return true; 19 | } 20 | 21 | if (hasPathSum(root->left, remain) || hasPathSum(root->right, remain)) { 22 | return true; 23 | } 24 | else return false; 25 | } 26 | 27 | void printTreePreOrder(struct TreeNode *p) { 28 | if (p != NULL) { 29 | printf("%d", p->val); 30 | printTreePreOrder(p->left); 31 | printTreePreOrder(p->right); 32 | } 33 | else printf("#"); 34 | } 35 | 36 | int main() { 37 | struct TreeNode *t = (struct TreeNode *)calloc(4, sizeof(struct TreeNode)); 38 | struct TreeNode *p = t; 39 | p->val = 1; 40 | p->left = ++t; 41 | t->val = -2; 42 | t->left = t->right = NULL; 43 | p->right = ++t; 44 | t->val = 0; 45 | t->left = t->right = NULL; 46 | printTreePreOrder(p); printf("\n"); 47 | 48 | printf("%d\n", hasPathSum(p, 1)); /* should be true */ 49 | printf("%d\n", hasPathSum(p, 0)); /* should be false */ 50 | printf("%d\n", hasPathSum(p, -1)); /* should be true */ 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /src/111.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | int minDepth(struct TreeNode *root) { 11 | if (root == NULL) 12 | return 0; 13 | 14 | int l = minDepth(root->left); 15 | int r = minDepth(root->right); 16 | 17 | if (l == 0 && r == 0) { /* leaf */ 18 | return 1; 19 | } 20 | else if (l && r == 0) { /* no right child */ 21 | return l + 1; 22 | } 23 | else if (r && l == 0) { /* no left child */ 24 | return r + 1; 25 | } 26 | else { 27 | return l < r ? (l + 1) : (r + 1); 28 | } 29 | } 30 | 31 | void printTreePreOrder(struct TreeNode *p) { 32 | if (p != NULL) { 33 | printf("%d", p->val); 34 | printTreePreOrder(p->left); 35 | printTreePreOrder(p->right); 36 | } 37 | else printf("#"); 38 | } 39 | 40 | int main() { 41 | struct TreeNode *t = (struct TreeNode *)calloc(4, sizeof(struct TreeNode)); 42 | struct TreeNode *p = t; 43 | p->val = 1; 44 | p->right = ++t; 45 | t->val = 2; 46 | t->right = NULL; 47 | p->right->left = ++t; 48 | t->val = 3; 49 | t->left = NULL; 50 | p->right->left->right = ++t; 51 | t->val = 4; 52 | t->left = t->right = NULL; 53 | printTreePreOrder(p); printf("\n"); 54 | 55 | /* should be 4 */ 56 | printf("%d\n", minDepth(p)); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /src/59.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Return an array of arrays. 6 | * Note: The returned array must be malloced, assume caller calls free(). 7 | */ 8 | int** generateMatrix(int n) { 9 | int **matrix = (int **)malloc(n * sizeof(int *)); 10 | if (n == 0) return matrix; 11 | 12 | int i; 13 | for (i = 0; i < n; i++) { 14 | matrix[i] = (int *)malloc(n * sizeof(int)); 15 | } 16 | 17 | int left = 0; 18 | int right = n - 1; 19 | int up = 0; 20 | int down = n - 1; 21 | int k = 1; 22 | 23 | while (left <= right && up <= down) { 24 | if (left == right && up == down) { 25 | matrix[left][up] = k++; 26 | } 27 | else { 28 | for (i = left; i <= right - 1; i++) 29 | matrix[up][i] = k++; 30 | for (i = up; i <= down - 1; i++) 31 | matrix[i][right] = k++; 32 | for (i = right; i >= left + 1; i--) 33 | matrix[down][i] = k++; 34 | for (i = down; i >= up + 1; i--) 35 | matrix[i][left] = k++; 36 | } 37 | left++; 38 | right--; 39 | up++; 40 | down--; 41 | } 42 | return matrix; 43 | } 44 | 45 | int main() { 46 | int n = 3; 47 | int **m = generateMatrix(n); 48 | 49 | int i, j; 50 | for (i = 0; i < n; i++) { 51 | for (j = 0; j < n; j++) { 52 | printf("%d ", m[i][j]); 53 | } 54 | printf("\n"); 55 | } 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/38.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* 28ms, a bit slow */ 6 | char* countAndSay(int n) { 7 | if (n == 0) return NULL; 8 | 9 | #define MAX 1000000 10 | char *buf = (char *)calloc(MAX, sizeof(char)); 11 | char *ans = (char *)calloc(MAX, sizeof(char)); 12 | 13 | ans[0] = '1'; 14 | 15 | char prev, *cur; 16 | int i, count, p; 17 | 18 | for (i = 0; i < n - 1; i++) { 19 | prev = *ans; 20 | cur = ans + 1; 21 | count = 1; 22 | p = 0; 23 | while (1) { 24 | if (prev != *cur) { 25 | buf[p++] = count + '0'; /* p += sprintf(buf + p, "%d", count); */ 26 | buf[p++] = prev; /* we can prove that there are 3 of same */ 27 | count = 1; /* numbers at most in the sequence, so */ 28 | } /* count always has 1 digit. */ 29 | else { 30 | count++; 31 | } 32 | 33 | if (*cur == '\0') break; 34 | 35 | prev = *cur; 36 | cur++; 37 | } 38 | 39 | char *t = ans; 40 | ans = buf; 41 | buf = t; 42 | 43 | memset(buf, 0, MAX); 44 | } 45 | 46 | free(buf); 47 | return ans; 48 | } 49 | 50 | int main() { 51 | int i; 52 | for (i = 0; i <= 30; i++) { 53 | printf("%d: %s\n", i, countAndSay(i)); 54 | } 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /src/81.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | bool search(int A[], int n, int target) { 5 | int l, r, m; 6 | l = 0; 7 | r = n - 1; 8 | while (l <= r) { 9 | m = (l + r) / 2; 10 | if (A[m] == target) return true; 11 | 12 | if (A[l] < A[m]) { /* left half is sorted */ 13 | if (A[l] <= target && target < A[m]) { /* target in left half */ 14 | r = m - 1; 15 | } 16 | else { 17 | l = m + 1; 18 | } 19 | } 20 | else if (A[l] > A[m]){ /* right half is sorted */ 21 | if (A[m] < target && target <= A[r]) { /* target in right half */ 22 | l = m + 1; 23 | } 24 | else { 25 | r = m - 1; 26 | } 27 | } 28 | else { /* we don't know which side is sorted */ 29 | l++; /* Q: why use 'l++' instead of 'r--' ? */ 30 | /* A: 'cos value of division always take floor of */ 31 | /* result, m may equals to l. */ 32 | /* e.g. l=3,r=4,m:=(3+4)/2=3 */ 33 | /* use 'r--', m will never equals to 4 */ 34 | } 35 | } 36 | return false; 37 | } 38 | 39 | int main() { 40 | int num[] = { 1, 3, 1, 1, 1 }; 41 | /* should be true */ 42 | printf("%d\n", search(num, sizeof(num) / sizeof(num[0]), 3)); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /src/151.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void reverseWords(char *s) { 6 | int len = strlen(s); 7 | int i, j; 8 | 9 | // remove the redundant spaces 10 | i = j = 0; 11 | while (i < len) 12 | { 13 | while (s[i] == ' ') { 14 | i++; 15 | } 16 | if (i >= len) break; 17 | while (s[i] != ' ' && s[i] != '\0') { 18 | s[j] = s[i]; 19 | j++; 20 | i++; 21 | } 22 | s[j] = ' '; 23 | j++; 24 | i++; 25 | } 26 | if (j > 0) j--; 27 | s[j] = '\0'; 28 | 29 | // reverse the whole string 30 | int new_len = strlen(s); 31 | char t; 32 | for (i = 0; i < new_len / 2; i++) 33 | { 34 | t = s[i]; 35 | s[i] = s[new_len - 1 - i]; 36 | s[new_len - 1 - i] = t; 37 | } 38 | 39 | // reverse the word separately 40 | int a, b; 41 | a = b = j = 0; 42 | for (i = 0; i < new_len + 1; i++) 43 | { 44 | if (s[i] == ' ' || s[i] == '\0') 45 | { 46 | b = i - 1; 47 | for (j = a; j < (b - a + 1) / 2 + a; j++){ 48 | t = s[j]; 49 | s[j] = s[b + a - j]; 50 | s[b + a - j] = t; 51 | } 52 | a = i + 1; 53 | } 54 | } 55 | } 56 | 57 | int main() 58 | { 59 | char s[] = " the sky is blue "; 60 | reverseWords(s); 61 | printf("%s\n", s); 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /src/24.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* swapPairs(struct ListNode* head) { 10 | if (head == NULL || head->next == NULL) return head; 11 | 12 | struct ListNode *p = head; 13 | struct ListNode *q = head->next; 14 | struct ListNode *new_head = q; 15 | struct ListNode *t = NULL; 16 | 17 | while (p && q) { 18 | t = q->next; 19 | q->next = p; 20 | if (t && t->next) { 21 | p->next = t->next; 22 | } 23 | else { 24 | p->next = t; 25 | break; 26 | } 27 | p = t; 28 | q = p->next; 29 | } 30 | 31 | return new_head; 32 | } 33 | 34 | int main() { 35 | int n = 5; 36 | struct ListNode *head = (struct ListNode *)calloc(n, sizeof(struct ListNode)); 37 | struct ListNode *p = head; 38 | int i; 39 | for (i = 0; i < n - 1; i++) { 40 | p->val = i + 1; 41 | p->next = p + 1; 42 | p = p->next; 43 | } 44 | p->val = n; 45 | p->next = NULL; 46 | 47 | printf("Linked List: "); 48 | p = head; 49 | while (p) { 50 | printf("%d ", p->val); 51 | p = p->next; 52 | } 53 | printf("\n"); 54 | 55 | p = swapPairs(head); 56 | 57 | printf("Swap Pairs: "); 58 | while (p) { 59 | printf("%d ", p->val); 60 | p = p->next; 61 | } 62 | printf("\n"); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /src/164.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int maximumGap(int num[], int n) { 6 | if (n < 2) return 0; 7 | 8 | /* radix sort */ 9 | int *sorted_num = (int *)calloc(n, sizeof(int)); 10 | int *temp = (int *)calloc(n, sizeof(int)); 11 | 12 | memcpy(sorted_num, num, sizeof(int) * n); 13 | 14 | int i, j; 15 | int shift; 16 | for (shift = 0; shift < 32; shift += 8) { 17 | int count[0x100] = {}; 18 | 19 | for (i = 0; i < n; i++) { 20 | count[(sorted_num[i] >> shift) & 0xFF] ++; 21 | } 22 | 23 | int idx = 0, t = 0; 24 | for (j = 0; j < 0x100; j++) { 25 | t = count[j]; 26 | count[j] = idx; 27 | idx += t; 28 | } 29 | 30 | for (i = 0; i < n; i++) { 31 | temp[count[(sorted_num[i] >> shift) & 0xFF] ++] = sorted_num[i]; 32 | } 33 | 34 | int *p = sorted_num; 35 | sorted_num = temp; 36 | temp = p; 37 | } 38 | 39 | int max_diff = 0; 40 | for (i = 1; i < n; i++) { 41 | if (sorted_num[i] - sorted_num[i - 1] > max_diff) { 42 | max_diff = sorted_num[i] - sorted_num[i - 1]; 43 | } 44 | } 45 | 46 | free(sorted_num); 47 | free(temp); 48 | return max_diff; 49 | } 50 | 51 | int main() { 52 | int A[] = { 4, 5, 3, 2, 9, 12, 32, 5 }; 53 | 54 | /* should be 20 = abs(12 - 32) */ 55 | printf("%d\n", maximumGap(A, sizeof(A)/sizeof(A[0]))); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/48.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void rotate(int **matrix, int n) { 5 | int i, j, k; 6 | int t; 7 | 8 | for (k = 0, i = n - 1; i >= 0; i -= 2, k++) { 9 | for (j = 0; j < i; j++) { 10 | /* backup left-up */ 11 | t = matrix[k][k + j]; 12 | /* left-down to left-up */ 13 | matrix[k][k + j] = matrix[i + k - j][k]; 14 | /* right-down to left-down */ 15 | matrix[i + k - j][k] = matrix[i + k][i + k - j]; 16 | /* right-up to right-down */ 17 | matrix[i + k][i + k - j] = matrix[k + j][i + k]; 18 | /* left-up to right-up */ 19 | matrix[k + j][i + k] = t; 20 | } 21 | } 22 | } 23 | 24 | int main() { 25 | int i, j, n; 26 | n = 5; 27 | int **mat = (int **)calloc(n, sizeof(int *)); 28 | for (i = 0; i < n; i++) { 29 | mat[i] = (int *)calloc(n, sizeof(int)); 30 | } 31 | 32 | for (i = 0; i < n; i++) { 33 | for (j = 0; j < n; j++) { 34 | mat[i][j] = n * i + j + 1; 35 | } 36 | } 37 | 38 | for (i = 0; i < n; i++) { 39 | for (j = 0; j < n; j++) { 40 | printf("%2d ", mat[i][j]); 41 | } 42 | printf("\n"); 43 | } 44 | printf("--------------\n"); 45 | 46 | rotate(mat, n); 47 | 48 | for (i = 0; i < n; i++) { 49 | for (j = 0; j < n; j++) { 50 | printf("%2d ", mat[i][j]); 51 | } 52 | printf("\n"); 53 | } 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /src/13.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int romanToInt(char *s) { 5 | int len = strlen(s); 6 | int ans = 0; 7 | int i = 0; 8 | while (i < len) { 9 | switch (s[i]) { 10 | case 'M': 11 | ans += 1000; 12 | break; 13 | case 'D': 14 | ans += 500; 15 | break; 16 | case 'C': 17 | if (s[i + 1] == 'D' || s[i + 1] == 'M'){ 18 | ans -= 100; 19 | } 20 | else { 21 | ans += 100; 22 | } 23 | break; 24 | case 'L': 25 | ans += 50; 26 | break; 27 | case 'X': 28 | if (s[i + 1] == 'L' || s[i + 1] == 'C'){ 29 | ans -= 10; 30 | } 31 | else { 32 | ans += 10; 33 | } 34 | break; 35 | case 'V': 36 | ans += 5; 37 | break; 38 | case 'I': 39 | if (s[i + 1] == 'V' || s[i + 1] == 'X'){ 40 | ans -= 1; 41 | } 42 | else { 43 | ans += 1; 44 | } 45 | break; 46 | default: 47 | break; 48 | } 49 | i++; 50 | } 51 | return ans; 52 | } 53 | 54 | int main() { 55 | char s1[] = "MMXIV"; 56 | char s2[] = "MMXV"; 57 | /* should be 2014 */ 58 | printf("%d\n", romanToInt(s1)); 59 | /* should be 2015 */ 60 | printf("%d\n", romanToInt(s2)); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /src/222.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | int countNodes(struct TreeNode* root) { 11 | if (root == NULL) return 0; 12 | 13 | struct TreeNode *l = root->left; 14 | struct TreeNode *r = root->right; 15 | 16 | int most_left_height = 1; 17 | int most_right_height = 1; 18 | 19 | while (l != NULL) { 20 | l = l->left; 21 | most_left_height++; 22 | } 23 | 24 | while (r != NULL) { 25 | r = r->right; 26 | most_right_height++; 27 | } 28 | 29 | if (most_left_height == most_right_height) { /* it's a full binary tree */ 30 | return (1 << most_left_height) - 1; 31 | } 32 | else { 33 | return countNodes(root->left) + countNodes(root->right) + 1; 34 | } 35 | } 36 | 37 | int main() { 38 | 39 | struct TreeNode *r = (struct TreeNode *)calloc(9, sizeof(struct TreeNode)); 40 | struct TreeNode *p = r; 41 | 42 | int i; 43 | for (i = 1; i <= 9; i++) { 44 | p->val = i; 45 | p++; 46 | } 47 | 48 | p = r; 49 | p->left = r + 1; 50 | p->right = r + 2; 51 | 52 | p = r + 1; 53 | p->left = r + 3; 54 | p->right = r + 4; 55 | 56 | p = r + 2; 57 | p->left = r + 5; 58 | p->right = r + 6; 59 | 60 | p = r + 3; 61 | p->left = r + 7; 62 | p->right = r + 8; 63 | 64 | /* should be 9 */ 65 | printf("%d\n", countNodes(r)); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /src/39.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector> combinationSum(vector& candidates, int target) { 9 | vector > ans; 10 | vector temp; 11 | 12 | combinationSumHelper(ans, temp, candidates, target); 13 | 14 | return ans; 15 | } 16 | 17 | void combinationSumHelper(vector > &ans, vector &temp, vector &candidates, int target) { 18 | if (target == 0) { 19 | ans.push_back(temp); 20 | return; 21 | } 22 | else if (target < 0) { 23 | return; 24 | } 25 | 26 | int max = 0; 27 | for (int k = 0; k < temp.size(); k++) { 28 | if (temp[k] > max) 29 | max = temp[k]; 30 | } 31 | 32 | for (int i = 0; i < candidates.size(); i++) { 33 | if (candidates[i] >= max) { 34 | temp.push_back(candidates[i]); 35 | combinationSumHelper(ans, temp, candidates, target - candidates[i]); 36 | temp.pop_back(); 37 | } 38 | } 39 | } 40 | }; 41 | 42 | int main() { 43 | vector candidates = {2, 3, 6, 7}; 44 | int target = 7; 45 | Solution s; 46 | vector > ans = s.combinationSum(candidates, target); 47 | 48 | for (int i = 0; i < ans.size(); i++) { 49 | for (int j = 0; j < ans[i].size(); j++) { 50 | printf("%d ", ans[i][j]); 51 | } 52 | printf("\n"); 53 | } 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /src/131.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector> partition(string s) { 10 | vector> ans; 11 | vector temp; 12 | partitionHelper(ans, temp, s); 13 | return ans; 14 | } 15 | 16 | void partitionHelper(vector> &ans, vector &temp, string s) { 17 | if (s.length() == 0) { 18 | ans.push_back(temp); 19 | return; 20 | } 21 | 22 | if (s.length() == 1) { 23 | temp.push_back(s); 24 | ans.push_back(temp); 25 | temp.pop_back(); 26 | return; 27 | } 28 | 29 | for (int i = 0; i < s.length(); i++) { 30 | if(isPalindrome(s.substr(0, i + 1))) { 31 | temp.push_back(s.substr(0, i + 1)); 32 | partitionHelper(ans, temp, s.substr(i + 1)); 33 | temp.pop_back(); 34 | } 35 | } 36 | } 37 | 38 | bool isPalindrome(string s) { 39 | int i = 0, j = s.length() - 1; 40 | while (i < j) { 41 | if (s[i] != s[j]) return false; 42 | i++; j--; 43 | } 44 | return true; 45 | } 46 | }; 47 | 48 | int main() { 49 | Solution s; 50 | auto ans = s.partition("aaaba"); 51 | 52 | for (int i = 0; i < ans.size(); i++) { 53 | for (int j = 0; j < ans[i].size(); j++) { 54 | cout << ans[i][j] << " "; 55 | } 56 | cout << endl; 57 | } 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /src/100.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct TreeNode { 6 | int val; 7 | struct TreeNode *left; 8 | struct TreeNode *right; 9 | }; 10 | 11 | bool isSameTree(struct TreeNode *p, struct TreeNode *q) { 12 | if (p == NULL && q == NULL) 13 | return true; 14 | else if (p && q) { 15 | if (p->val == q->val 16 | && isSameTree(p->left, q->left) 17 | && isSameTree(p->right, q->right)) 18 | return true; 19 | else return false; 20 | } 21 | else return false; 22 | } 23 | 24 | void printTreePreOrder(struct TreeNode *p) { 25 | if (p != NULL) { 26 | printf("%d", p->val); 27 | printTreePreOrder(p->left); 28 | printTreePreOrder(p->right); 29 | } 30 | else printf("#"); 31 | } 32 | 33 | int main() { 34 | struct TreeNode *t = (struct TreeNode *)calloc(3, sizeof(struct TreeNode)); 35 | struct TreeNode *p = t; 36 | p->val = 1; 37 | p->left = ++t; 38 | t->val = 2; 39 | t->left = t->right = NULL; 40 | p->right = ++t; 41 | t->val = 3; 42 | t->left = t->right = NULL; 43 | printTreePreOrder(p); printf("\n"); 44 | 45 | t = (struct TreeNode *)calloc(3, sizeof(struct TreeNode)); 46 | struct TreeNode *q = t; 47 | q->val = 1; 48 | q->left = ++t; 49 | t->val = 2; 50 | t->left = t->right = NULL; 51 | q->right = ++t; 52 | t->val = 4; 53 | t->left = t->right = NULL; 54 | printTreePreOrder(q); printf("\n"); 55 | 56 | printf("%d\n", isSameTree(p, q)); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /src/240.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | bool searchMatrix(int **matrix, int matrixRowSize, int matrixColSize, int target) { 7 | int i, j; 8 | i = 0; j = matrixColSize - 1; /* right-top */ 9 | bool found = false; 10 | while (i < matrixRowSize && j >= 0) { 11 | if (matrix[i][j] == target) { 12 | found = true; 13 | break; 14 | } 15 | if (matrix[i][j] < target) 16 | i++; 17 | else 18 | j--; 19 | } 20 | 21 | return found; 22 | } 23 | 24 | int main() { 25 | int rows = 5; 26 | int cols = 5; 27 | 28 | int **matrix = (int **)malloc(rows * sizeof(int *)); 29 | int i; 30 | for (i = 0; i < rows; i++) { 31 | matrix[i] = (int *)malloc(cols * sizeof(int)); 32 | } 33 | 34 | matrix[0][0] = 1; matrix[0][1] = 4; matrix[0][2] = 7; matrix[0][3] = 11; matrix[0][4] = 15; 35 | matrix[1][0] = 2; matrix[1][1] = 5; matrix[1][2] = 8; matrix[1][3] = 12; matrix[1][4] = 19; 36 | matrix[2][0] = 3; matrix[2][1] = 6; matrix[2][2] = 9; matrix[2][3] = 16; matrix[2][4] = 22; 37 | matrix[3][0] = 10; matrix[3][1] = 13; matrix[3][2] = 14; matrix[3][3] = 17; matrix[3][4] = 24; 38 | matrix[4][0] = 18; matrix[4][1] = 21; matrix[4][2] = 23; matrix[4][3] = 26; matrix[4][4] = 30; 39 | 40 | assert(searchMatrix(matrix, rows, cols, 5) == true); 41 | assert(searchMatrix(matrix, rows, cols, 20) == false); 42 | 43 | for (i = 0; i < rows; i++) { 44 | free(matrix[i]); 45 | } 46 | free(matrix); 47 | 48 | printf("all tests passed!\n"); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /src/114.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct TreeNode { 6 | int val; 7 | struct TreeNode *left; 8 | struct TreeNode *right; 9 | }; 10 | 11 | void flattenHelper(struct TreeNode* root, struct TreeNode **start, struct TreeNode **end){ 12 | if (root == NULL) { 13 | *start = *end = NULL; 14 | return; 15 | } 16 | struct TreeNode *lstart, *lend, *rstart, *rend; 17 | lstart = lend = rstart = rend = NULL; 18 | 19 | flattenHelper(root->left, &lstart, &lend); 20 | flattenHelper(root->right, &rstart, &rend); 21 | 22 | root->left = NULL; 23 | 24 | if (lend != NULL) { 25 | root->right = lstart; 26 | lend->right = rstart; 27 | } 28 | else { 29 | root->right = rstart; 30 | } 31 | 32 | *start = root; 33 | 34 | if (rend != NULL) { 35 | *end = rend; 36 | } 37 | else if (lend != NULL) { 38 | *end = lend; 39 | } 40 | else { 41 | *end = root; 42 | } 43 | } 44 | 45 | void flatten(struct TreeNode* root) { 46 | struct TreeNode *start, *end; 47 | start = end = NULL; 48 | 49 | flattenHelper(root, &start, &end); 50 | } 51 | 52 | int main() { 53 | struct TreeNode *root = (struct TreeNode *)calloc(3, sizeof(struct TreeNode)); 54 | root->val = 1; 55 | root->left = root + 1; 56 | root->left->val = 2; 57 | root->left->left = root + 2; 58 | root->left->left->val = 3; 59 | 60 | flatten(root); 61 | 62 | while (root) { 63 | assert(root->left == NULL); 64 | printf("%d ", root->val); 65 | root = root->right; 66 | } 67 | printf("\n"); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /src/69.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Newton's method */ 5 | int mySqrt(int square) { 6 | #define EPSILON 0.00000001f 7 | double x = 1.0; 8 | double f, d; 9 | 10 | for (int i = 0; i < 32; i++) { 11 | f = x * x - square; 12 | if ((f > 0 && f < EPSILON) || (f < 0 && f > -EPSILON)) break; 13 | d = 2 * x; 14 | x = x - f / d; 15 | } 16 | 17 | return x; 18 | } 19 | 20 | /* Fast Newton's method 21 | * https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Approximations_that_depend_on_the_floating_point_representation 22 | */ 23 | int mySqrt0(int x) { 24 | float f = x; 25 | int val_int = *(int *)&f; 26 | 27 | int a = 2; 28 | val_int = (1 << 29) + (val_int >> 1) - (1 << 22) + a; 29 | 30 | f = *(float *)&val_int; 31 | double d = f; 32 | d = 0.5 * d + 0.5 * x / d; 33 | d = 0.5 * d + 0.5 * x / d; 34 | d = 0.5 * d + 0.5 * x / d; 35 | return d; 36 | } 37 | 38 | /* Binary Search */ 39 | int mySqrt1(int x) { 40 | if (x <= 1) { 41 | return x; 42 | } 43 | 44 | int l, m, r; 45 | l = 1; 46 | r = x; 47 | 48 | while (l < r) { 49 | m = (l + r) / 2; 50 | 51 | if (x / m < m) 52 | r = m; 53 | else 54 | l = m + 1; 55 | } 56 | 57 | return r - 1; 58 | } 59 | 60 | int main() { 61 | assert(mySqrt1(0) == 0); 62 | assert(mySqrt1(1) == 1); 63 | assert(mySqrt1(2) == 1); 64 | assert(mySqrt1(3) == 1); 65 | assert(mySqrt1(8) == 2); 66 | assert(mySqrt1(2147395599) == 46339); 67 | assert(mySqrt1(2147395600) == 46340); 68 | 69 | printf("all tests passed!\n"); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /src/86.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* partition(struct ListNode* head, int x) { 10 | if (head == NULL) return NULL; 11 | 12 | struct ListNode *left, *right; 13 | struct ListNode *lp, *rp; 14 | struct ListNode *p; 15 | 16 | left = (struct ListNode *)calloc(1, sizeof(struct ListNode)); 17 | right = (struct ListNode *)calloc(1, sizeof(struct ListNode)); 18 | lp = left; 19 | rp = right; 20 | p = head; 21 | 22 | while (p) { 23 | if (p->val < x) { 24 | lp->next = p; 25 | lp = lp->next; 26 | } 27 | else { 28 | rp->next = p; 29 | rp = rp->next; 30 | } 31 | p = p->next; 32 | } 33 | 34 | lp->next = right->next; 35 | rp->next = NULL; 36 | head = left->next; 37 | 38 | free(left); free(right); 39 | 40 | return head; 41 | } 42 | 43 | int main() { 44 | struct ListNode *head = (struct ListNode *)calloc(6, sizeof(struct ListNode)); 45 | struct ListNode *p = head; 46 | p->val = 1; 47 | p->next = p + 1; 48 | p = p->next; 49 | p->val = 4; 50 | p->next = p + 1; 51 | p = p->next; 52 | p->val = 3; 53 | p->next = p + 1; 54 | p = p->next; 55 | p->val = 2; 56 | p->next = p + 1; 57 | p = p->next; 58 | p->val = 5; 59 | p->next = p + 1; 60 | p = p->next; 61 | p->val = 2; 62 | p->next = NULL; 63 | 64 | int x = 3; 65 | p = partition(head, x); 66 | 67 | while (p) { 68 | printf("%d ", p->val); 69 | p = p->next; 70 | } 71 | printf("\n"); 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /src/290.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | bool wordPattern(string pattern, string str) { 12 | vector words; 13 | map word2pattern; 14 | map pattern2word; 15 | 16 | int i, prev = 0; 17 | for (i = 0; i <= str.length(); i++) { 18 | if (str[i] == ' ' || str[i] == '\0') { 19 | words.push_back(str.substr(prev, i - prev)); 20 | prev = i + 1; 21 | } 22 | } 23 | 24 | if (pattern.length() != words.size()) return false; 25 | 26 | for (i = 0; i < words.size(); i++) { 27 | if (word2pattern.find(words[i]) == word2pattern.end() && 28 | pattern2word.find(pattern[i]) == pattern2word.end()) { 29 | word2pattern[words[i]] = pattern[i]; 30 | pattern2word[pattern[i]] = words[i]; 31 | } 32 | else { 33 | if (word2pattern[words[i]] != pattern[i] || 34 | pattern2word[pattern[i]] != words[i]) { 35 | return false; 36 | } 37 | } 38 | } 39 | 40 | return true; 41 | } 42 | }; 43 | 44 | int main() { 45 | 46 | Solution s; 47 | assert(s.wordPattern("abba", "dog cat cat dog") == true); 48 | assert(s.wordPattern("abba", "dog cat cat fish") == false); 49 | assert(s.wordPattern("aaaa", "dog cat cat dog") == false); 50 | assert(s.wordPattern("abba", "dog dog dog dog") == false); 51 | 52 | printf("all tests passed!\n"); 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /src/60.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | string getPermutation(int n, int k) { 10 | if (k == 0) return ""; 11 | string ans; 12 | vector nums(n); /* numbers from 1 to n */ 13 | vector flag(n, false); 14 | 15 | for (int i = 0; i < n; i++) { 16 | nums[i] = i + 1; 17 | } 18 | getPermutationHelper(ans, nums, flag, n, k); 19 | 20 | return ans; 21 | } 22 | 23 | void getPermutationHelper(string &ans, vector nums, vector &flag, int n, int k) { 24 | if (n == 0) return; 25 | 26 | int fact = 1; /* factorial of (n - 1) */ 27 | for (int i = 1; i <= n - 1; i++) { 28 | fact *= i; 29 | } 30 | 31 | int first = 0; /* pick the first available number as head of permutation */ 32 | while (flag[first]) { /* skip unavailable numbers */ 33 | first++; 34 | } 35 | 36 | while (k > fact) { 37 | first++; 38 | while (flag[first]) { /* skip unavailable numbers */ 39 | first++; 40 | } 41 | k -= fact; 42 | } 43 | 44 | flag[first] = true; 45 | ans.push_back(nums[first] + '0'); 46 | 47 | getPermutationHelper(ans, nums, flag, n - 1, k); 48 | } 49 | }; 50 | 51 | int main() { 52 | int n = 3; 53 | int factN = 1; 54 | for (int i = 1; i <= n; i++) { 55 | factN *= i; 56 | } 57 | 58 | Solution s; 59 | 60 | for (int k = 1; k <= factN; k++) { 61 | cout << s.getPermutation(n, k) << endl; 62 | } 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /src/105.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | int searchNode(int inorder[], int inorderSize, int key){ 11 | int i; 12 | for (i = 0; i < inorderSize; i++) { 13 | if (key == inorder[i]) { 14 | return i; 15 | } 16 | } 17 | return -1; 18 | } 19 | 20 | struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) { 21 | 22 | if (preorder == NULL || inorder == NULL 23 | || preorderSize == 0 || inorderSize == 0) return NULL; 24 | 25 | struct TreeNode *root 26 | = (struct TreeNode *)malloc(sizeof(struct TreeNode)); 27 | root->val = preorder[0]; 28 | 29 | int index = searchNode(inorder, inorderSize, preorder[0]); 30 | if (index == -1) return NULL; 31 | 32 | root->left = buildTree(preorder + 1, index, inorder, index); 33 | root->right = buildTree(preorder + index + 1, inorderSize - index - 1, 34 | inorder + index + 1, inorderSize - index - 1); 35 | 36 | return root; 37 | } 38 | 39 | void preOrderPrint(struct TreeNode *root) { 40 | if (root) { 41 | printf("%d ", root->val); 42 | preOrderPrint(root->left); 43 | preOrderPrint(root->right); 44 | } 45 | } 46 | 47 | int main() { 48 | 49 | int pre[] = { 20, 8, 4, 12, 10, 14, 22 }; 50 | int in[] = { 4, 8, 10, 12, 14, 20, 22 }; 51 | 52 | struct TreeNode *r 53 | = buildTree(pre, sizeof(pre)/sizeof(pre[0]), in, sizeof(in)/sizeof(in[0])); 54 | 55 | preOrderPrint(r); printf("\n"); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/125.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char ch2lower(char ch) { 6 | if (ch >= 'A' && ch <= 'Z') 7 | ch += 0x20; 8 | 9 | return ch; 10 | } 11 | 12 | bool isPalindrome(char *s) { 13 | int len = strlen(s); 14 | int head, tail; 15 | head = tail = 0; 16 | tail = len - 1; 17 | 18 | while (head <= tail) { 19 | while (ch2lower(s[head]) < '0' 20 | || (ch2lower(s[head]) > '9' && ch2lower(s[head]) < 'a') 21 | || ch2lower(s[head]) > 'z') 22 | { 23 | head++; 24 | if (head > tail) break; 25 | } 26 | 27 | while (ch2lower(s[tail]) < '0' 28 | || (ch2lower(s[tail]) > '9' && ch2lower(s[tail]) < 'a') 29 | || ch2lower(s[tail]) > 'z') 30 | { 31 | tail--; 32 | if (head > tail) break; 33 | } 34 | 35 | if (head > tail) break; 36 | 37 | if (ch2lower(s[head]) != ch2lower(s[tail])) return false; 38 | 39 | head++; 40 | tail--; 41 | } 42 | 43 | return true; 44 | } 45 | 46 | int main() { 47 | char s1[] = "A man, a plan, a canal: Panama"; 48 | char s2[] = "race a car"; 49 | char s3[] = ""; 50 | char s4[] = "a"; 51 | char s5[] = ".,"; 52 | char s6[] = "."; 53 | char s7[] = " "; 54 | 55 | printf("%d\n", isPalindrome(s1)); 56 | printf("%d\n", isPalindrome(s2)); 57 | printf("%d\n", isPalindrome(s3)); 58 | printf("%d\n", isPalindrome(s4)); 59 | printf("%d\n", isPalindrome(s5)); 60 | printf("%d\n", isPalindrome(s6)); 61 | printf("%d\n", isPalindrome(s7)); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /src/228.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Return an array of size *returnSize. 6 | * Note: The returned array must be malloced, assume caller calls free(). 7 | */ 8 | char** summaryRanges(int* nums, int numsSize, int* returnSize) { 9 | if (nums == NULL || numsSize == 0) return NULL; 10 | 11 | #define MAXNUM 1024 12 | #define MAXLEN 32 13 | 14 | char **ans = (char **)calloc(MAXNUM, sizeof(char *)); 15 | *returnSize = 0; 16 | 17 | int i; 18 | int start = nums[0]; 19 | 20 | for (i = 1; i < numsSize; i++) { 21 | if (nums[i] != nums[i - 1] + 1) { 22 | ans[*returnSize] = (char *)calloc(MAXLEN, sizeof(char)); 23 | if (start != nums[i - 1]) 24 | sprintf(ans[*returnSize], "%d->%d", start, nums[i - 1]); 25 | else 26 | sprintf(ans[*returnSize], "%d", start); 27 | 28 | (*returnSize) ++; 29 | start = nums[i]; 30 | } 31 | } 32 | 33 | ans[*returnSize] = (char *)calloc(MAXLEN, sizeof(char)); 34 | if (start != nums[i - 1]) 35 | sprintf(ans[*returnSize], "%d->%d", start, nums[i - 1]); 36 | else 37 | sprintf(ans[*returnSize], "%d", start); 38 | 39 | (*returnSize) ++; 40 | 41 | return ans; 42 | } 43 | 44 | int main() { 45 | int nums[] = { 0, 1, 2, 4, 5, 7 }; 46 | int returnSize = 0; 47 | 48 | char** ret = summaryRanges(nums, sizeof(nums) / sizeof(nums[0]), &returnSize); 49 | 50 | int i; 51 | for (i = 0; i < returnSize; i++) { 52 | printf("%s, ", ret[i]); 53 | free(ret[i]); 54 | } 55 | printf("\n"); 56 | free(ret); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /src/61.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* rotateRight(struct ListNode* head, int k) { 10 | if (head == NULL || k == 0) return head; 11 | 12 | struct ListNode **p = &head; 13 | struct ListNode *new_head = NULL; 14 | 15 | int len = 0; 16 | while (*p) { 17 | p = &((*p)->next); 18 | len++; 19 | } 20 | 21 | k = k % len; /* important */ 22 | if (k == 0) return head; 23 | 24 | *p = head; /* tail->next = head, make a circle */ 25 | 26 | p = &head; 27 | while (len > k) { 28 | p = &((*p)->next); 29 | len--; 30 | } 31 | new_head = *p; /* new_head = new_tail->next */ 32 | *p = NULL; /* new_tail = NULL */ 33 | 34 | return new_head; 35 | } 36 | 37 | int main() { 38 | 39 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 40 | 41 | struct ListNode **p = &l1; 42 | int i; 43 | for (i = 1; i <= 5; i++) { 44 | (*p)->val = i; 45 | (*p)->next = *p + 1; 46 | p = &(*p)->next; 47 | } 48 | *p = NULL; 49 | 50 | printf("List: "); 51 | struct ListNode *q = l1; 52 | while (q != NULL) { 53 | printf("%d->", q->val); 54 | q = q->next; 55 | } 56 | printf("N\n"); 57 | 58 | int k = 2; 59 | printf("Rotate right by %d.\n", k); 60 | 61 | struct ListNode *ret = rotateRight(l1, k); 62 | 63 | printf("Result: "); 64 | q = ret; 65 | while (q != NULL) { 66 | printf("%d->", q->val); 67 | q = q->next; 68 | } 69 | printf("N\n"); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /src/173.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct TreeNode { 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | }; 12 | 13 | class BSTIterator { 14 | stack path; 15 | public: 16 | BSTIterator(TreeNode *root) { 17 | while (root) { 18 | path.push(root); 19 | root = root->left; 20 | } 21 | } 22 | 23 | /** @return whether we have a next smallest number */ 24 | bool hasNext() { 25 | return !path.empty(); 26 | } 27 | 28 | /** @return the next smallest number */ 29 | int next() { 30 | int ans = -1; 31 | if (hasNext()) { 32 | TreeNode *p = path.top(); 33 | path.pop(); 34 | ans = p->val; 35 | p = p->right; 36 | while (p) { 37 | path.push(p); 38 | p = p->left; 39 | } 40 | } 41 | return ans; 42 | } 43 | }; 44 | 45 | int main() { 46 | /* 47 | * 5 48 | * / \ 49 | * 2 7 50 | * / \ / \ 51 | * 1 4 6 8 52 | * / 53 | * 3 54 | */ 55 | 56 | TreeNode *root = new TreeNode(5); 57 | root->left = new TreeNode(2); 58 | root->left->left = new TreeNode(1); 59 | root->left->right = new TreeNode(4); 60 | root->left->right->left = new TreeNode(3); 61 | 62 | root->right = new TreeNode(7); 63 | root->right->left = new TreeNode(6); 64 | root->right->right = new TreeNode(8); 65 | 66 | BSTIterator i = BSTIterator(root); 67 | while (i.hasNext()) cout << i.next(); 68 | cout << endl; 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /src/6.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char *convert(char *s, int nRows) { 6 | int len = strlen(s); 7 | char *ret = (char *)malloc(len + 1); 8 | int i, j; 9 | j = 0; /* index of return string */ 10 | 11 | /** 12 | * don't know why return s or modify input pointer will cause runtime error, 13 | * so I have to copy a string and try not to modify s. I tried 5 times to 14 | * finally find out what happened, sad for my acceptance rate... 15 | */ 16 | if (nRows == 1) { 17 | while (j < len) { 18 | ret[j] = s[j]; 19 | j++; 20 | } 21 | ret[len] = '\0'; 22 | return ret; 23 | } 24 | 25 | int t = (nRows - 1) * 2; 26 | int shift, offset; 27 | 28 | for (i = 0; i < nRows; i++) { 29 | offset = 0; 30 | shift = (nRows - i - 1) * 2; 31 | while (j < len && i + offset < len) { 32 | ret[j] = s[i + offset]; 33 | j++; 34 | 35 | if (shift == 0) { 36 | shift = t; 37 | } 38 | 39 | offset += shift; 40 | 41 | if (shift != t) { 42 | shift = t - shift; 43 | } 44 | } 45 | } 46 | 47 | ret[len] = '\0'; 48 | 49 | return ret; 50 | } 51 | 52 | int main() { 53 | char str1[] = "PAYPALISHIRING"; 54 | char str2[] = "A"; 55 | char str3[] = "zvmwnuufnnxvloyvgmliuqandlyavfauaosnlnv"; 56 | printf("%s\n", convert(str1, 3)); 57 | printf("%s\n", convert(str1, 4)); 58 | printf("%s\n", convert(str1, 5)); 59 | printf("%s\n", convert(str2, 1)); 60 | printf("%s\n", convert(str3, 1)); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /src/106.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | int searchNode(int inorder[], int inorderSize, int key){ 11 | int i; 12 | for (i = 0; i < inorderSize; i++) { 13 | if (key == inorder[i]) { 14 | return i; 15 | } 16 | } 17 | return -1; 18 | } 19 | 20 | struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) { 21 | 22 | if (inorder == NULL || postorder == NULL 23 | || inorderSize == 0 || postorderSize == 0) return NULL; 24 | 25 | struct TreeNode *root 26 | = (struct TreeNode *)malloc(sizeof(struct TreeNode)); 27 | root->val = postorder[postorderSize - 1]; 28 | 29 | int index = searchNode(inorder, inorderSize, postorder[postorderSize - 1]); 30 | if (index == -1) return NULL; 31 | 32 | root->left = buildTree(inorder, index, postorder, index); 33 | root->right = buildTree(inorder + index + 1, inorderSize - index - 1, 34 | postorder + index, inorderSize - index - 1); 35 | 36 | return root; 37 | } 38 | 39 | void postOrderPrint(struct TreeNode *root) { 40 | if (root) { 41 | postOrderPrint(root->left); 42 | postOrderPrint(root->right); 43 | printf("%d ", root->val); 44 | } 45 | } 46 | 47 | int main() { 48 | 49 | int in[] = { 4, 8, 10, 12, 14, 20, 22 }; 50 | int post[] = { 4, 10, 14, 12, 8, 22, 20 }; 51 | 52 | struct TreeNode *r 53 | = buildTree(in, sizeof(in)/sizeof(in[0]), post, sizeof(post)/sizeof(post[0])); 54 | 55 | postOrderPrint(r); printf("\n"); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/19.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode *removeNthFromEnd(struct ListNode *head, int n) { 10 | if (n == 0) return head; 11 | 12 | struct ListNode *fast, *slow; 13 | fast = slow = head; 14 | 15 | while (n--) { 16 | fast = fast->next; 17 | } 18 | 19 | if (fast == NULL) { /* reach the tail, so we delete the head */ 20 | head = head->next; 21 | return head; 22 | } 23 | 24 | while (fast->next != NULL) { 25 | fast = fast->next; 26 | slow = slow->next; 27 | } 28 | 29 | /* slow pointer is at the previous node of the one to be deleted */ 30 | slow->next = slow->next->next; 31 | 32 | return head; 33 | } 34 | 35 | int main() { 36 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 37 | struct ListNode *p = l1; 38 | int i; 39 | for (i = 1; i <= 4; i++) { 40 | p->val = i; 41 | p->next = p + 1; 42 | p++; 43 | } 44 | p->val = 5; 45 | p->next = NULL; 46 | 47 | p = removeNthFromEnd(l1, 1); /* delete the tail */ 48 | 49 | while (p) { 50 | printf("%d ", p->val); 51 | p = p->next; 52 | } 53 | printf("\n"); 54 | 55 | 56 | p = removeNthFromEnd(l1, 0); /* delete nothing */ 57 | 58 | while (p) { 59 | printf("%d ", p->val); 60 | p = p->next; 61 | } 62 | printf("\n"); 63 | 64 | p = removeNthFromEnd(l1, 4); /* delete the head */ 65 | 66 | while (p) { 67 | printf("%d ", p->val); 68 | p = p->next; 69 | } 70 | printf("\n"); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /src/217.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct HashNode { 6 | int data; 7 | struct HashNode *next; 8 | }; 9 | 10 | static inline int hash(int num, int size) { 11 | int index = num % size; 12 | return (index > 0) ? (index) : (-index); 13 | } 14 | 15 | bool containsDuplicate(int* nums, int numsSize) { 16 | if (numsSize < 2) return false; 17 | bool duplicated = false; 18 | 19 | int hash_size = numsSize / 2 + 1; /* proper size can be faster */ 20 | struct HashNode **hash_table 21 | = (struct HashNode **)calloc(hash_size, sizeof(struct HashNode *)); 22 | 23 | int i; 24 | for (i = 0; i < numsSize; i++) { 25 | int index = hash(nums[i], hash_size); 26 | struct HashNode **p = hash_table + index; 27 | 28 | while (*p) { 29 | if ((*p)->data == nums[i]) { 30 | duplicated = true; 31 | goto OUT; 32 | } 33 | p = &((*p)->next); 34 | } 35 | 36 | struct HashNode *new_node 37 | = (struct HashNode *)malloc(sizeof(struct HashNode)); 38 | new_node->data = nums[i]; 39 | new_node->next = NULL; 40 | 41 | *p = new_node; 42 | } 43 | 44 | OUT: 45 | for (i = 0; i < hash_size; i++) { 46 | struct HashNode *t = hash_table[i]; 47 | struct HashNode *x = NULL; 48 | while (t) { 49 | x = t->next; 50 | free(t); 51 | t = x; 52 | } 53 | } 54 | free(hash_table); 55 | 56 | return duplicated; 57 | } 58 | 59 | int main() { 60 | int nums[] = { 1, 3, 5, 7, 9, 7 }; 61 | /* should be 1 */ 62 | printf("%d\n", containsDuplicate(nums, sizeof(nums) / sizeof(nums[0]))); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /src/78.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector> subsets(vector& nums) { 9 | unsigned int n = nums.size(); 10 | vector> ans; 11 | if (n == 0) return ans; 12 | 13 | quicksort(nums, 0, n - 1); 14 | 15 | vector temp; 16 | for (unsigned int i = 0; i < (1 << n); i++) { 17 | unsigned int t = i; 18 | unsigned int k = 0; 19 | while (t) { 20 | if (t & 1) { 21 | temp.push_back(nums[k]); 22 | } 23 | t >>= 1; 24 | k++; 25 | } 26 | 27 | ans.push_back(temp); 28 | temp.clear(); 29 | } 30 | 31 | return ans; 32 | } 33 | 34 | void quicksort(vector &nums, int start, int end) { 35 | if (start >= end) return; 36 | int i = start; 37 | int j = end; 38 | int sentinal = nums[start]; 39 | while (i < j) { 40 | while (i < j && nums[j] >= sentinal) 41 | j--; 42 | 43 | nums[i] = nums[j]; 44 | while (i < j && nums[i] <= sentinal) 45 | i++; 46 | 47 | nums[j] = nums[i]; 48 | } 49 | 50 | nums[i] = sentinal; 51 | 52 | quicksort(nums, start, i - 1); 53 | quicksort(nums, i + 1, end); 54 | } 55 | }; 56 | 57 | int main() { 58 | vector nums = {2, 1, 3}; 59 | Solution s; 60 | auto ans = s.subsets(nums); 61 | for (int i = 0; i < ans.size(); i++) { 62 | for (int j = 0 ; j < ans[i].size(); j++) { 63 | printf("%d ", ans[i][j]); 64 | } 65 | printf("\n"); 66 | } 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /src/101.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct TreeNode { 6 | int val; 7 | struct TreeNode *left; 8 | struct TreeNode *right; 9 | }; 10 | 11 | bool isSymmetric0(struct TreeNode* left, struct TreeNode* right){ 12 | if (left == NULL && right == NULL) return true; 13 | 14 | if (left && right 15 | && (left->val == right->val) 16 | && isSymmetric0(left->left, right->right) 17 | && isSymmetric0(left->right, right->left)) 18 | return true; 19 | else 20 | return false; 21 | } 22 | 23 | bool isSymmetric(struct TreeNode* root) { 24 | if (root == NULL) return true; 25 | 26 | return isSymmetric0(root->left, root->right); 27 | } 28 | 29 | void printTreePreOrder(struct TreeNode* root) { 30 | if (root) { 31 | printf("%d", root->val); 32 | printTreePreOrder(root->left); 33 | printTreePreOrder(root->right); 34 | } 35 | else 36 | printf("#"); 37 | } 38 | 39 | int main() { 40 | 41 | struct TreeNode* r = (struct TreeNode*)calloc(7, sizeof(struct TreeNode)); 42 | struct TreeNode* p = r; 43 | 44 | p->val = 1; 45 | p->left = r + 1; 46 | p->right = r + 2; 47 | 48 | p = r + 1; 49 | p->val = 2; 50 | p->left = r + 3; 51 | p->right = r + 4; 52 | 53 | p = r + 2; 54 | p->val = 2; 55 | p->left = r + 5; 56 | p->right = r + 6; 57 | 58 | p = r + 3; 59 | p->val = 3; 60 | 61 | p = r + 4; 62 | p->val = 4; 63 | 64 | p = r + 5; 65 | p->val = 4; 66 | 67 | p = r + 6; 68 | p->val = 3; 69 | 70 | printTreePreOrder(r); printf("\n"); 71 | 72 | /* should be true */ 73 | printf("%d\n", isSymmetric(r)); 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /src/179.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define N 12 /* max number of digits in 10-base integer */ 6 | 7 | int compare(int a, int b) { 8 | char stra[N] = { 0 }; 9 | char strb[N] = { 0 }; 10 | sprintf(stra, "%d", a); 11 | sprintf(strb, "%d", b); 12 | 13 | char aplusb[N + N] = { 0 }; 14 | char bplusa[N + N] = { 0 }; 15 | strcpy(aplusb, stra); 16 | strcat(aplusb, strb); 17 | 18 | strcpy(bplusa, strb); 19 | strcat(bplusa, stra); 20 | 21 | return strcmp(aplusb, bplusa); 22 | } 23 | 24 | void quicksort(int *nums, int left, int right) { 25 | if (left > right) return; 26 | 27 | int i = left; 28 | int j = right; 29 | int pivot = nums[left]; 30 | while (i < j) { 31 | while (i < j && compare(nums[j], pivot) <= 0) j--; 32 | nums[i] = nums[j]; 33 | while (i < j && compare(nums[i], pivot) >= 0) i++; 34 | nums[j] = nums[i]; 35 | } 36 | nums[i] = pivot; 37 | quicksort(nums, left, i - 1); 38 | quicksort(nums, i + 1, right); 39 | } 40 | 41 | char* largestNumber(int* nums, int numsSize) { 42 | quicksort(nums, 0, numsSize - 1); 43 | char *ans = (char *)calloc(numsSize * N, sizeof(char)); 44 | int i; 45 | for (i = 0; i < numsSize; i++) { 46 | char buf[N] = { 0 }; 47 | sprintf(buf, "%d", nums[i]); 48 | strcat(ans, buf); 49 | } 50 | 51 | /* skip leading zeros */ 52 | while (*ans == '0' && *(ans + 1) == '0') ans++; 53 | 54 | return ans; 55 | } 56 | 57 | int main() { 58 | int nums0[] = { 3, 30, 34, 5, 9 }; 59 | printf("%s\n", largestNumber(nums0, sizeof(nums0) / sizeof(nums0[0]))); 60 | 61 | int nums1[] = { 0, 0 }; 62 | printf("%s\n", largestNumber(nums1, sizeof(nums1) / sizeof(nums1[0]))); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /src/200.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void dfs(char **grid, bool **visited, int i, int j, int numRows, int numColumns) { 7 | if (i >= 0 && i < numRows && j >= 0 && j < numColumns && !visited[i][j]) { 8 | visited[i][j] = 1; 9 | if (grid[i][j] == '1') { /* island */ 10 | dfs(grid, visited, i, j - 1, numRows, numColumns); /* left */ 11 | dfs(grid, visited, i, j + 1, numRows, numColumns); /* right */ 12 | dfs(grid, visited, i - 1, j, numRows, numColumns); /* up */ 13 | dfs(grid, visited, i + 1, j, numRows, numColumns); /* down */ 14 | } 15 | } 16 | } 17 | 18 | int numIslands(char **grid, int numRows, int numColumns) { 19 | if (grid == NULL || numRows == 0 || strlen(grid[0]) == 0) 20 | return 0; 21 | 22 | int i, j; 23 | int count = 0; 24 | 25 | bool **visited = (bool **)calloc(numRows, sizeof(bool *)); 26 | for (i = 0; i < numRows; i++) { 27 | visited[i] = (bool *)calloc(numColumns, sizeof(bool)); 28 | } 29 | 30 | for (i = 0; i < numRows; i++) { 31 | for (j = 0; j < numColumns; j++) { 32 | if (!visited[i][j]) { /* has not been visited */ 33 | if (grid[i][j] == '1') /* it's an island */ 34 | count++; 35 | dfs(grid, visited, i, j, numRows, numColumns); 36 | } 37 | } 38 | } 39 | return count; 40 | } 41 | 42 | int main() { 43 | int row = 3; 44 | int col = 3; 45 | char **grid = (char **)calloc(1, sizeof(char *)); 46 | 47 | grid[0] = "111"; 48 | grid[1] = "010"; 49 | grid[2] = "111"; 50 | 51 | /* should be 1 */ 52 | printf("%d\n", numIslands(grid, row, col)); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /src/31.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) { 4 | int c = *a; 5 | *a = *b; 6 | *b = c; 7 | } 8 | 9 | void nextPermutation(int* nums, int numsSize) { 10 | if (nums == NULL || numsSize == 0) return; 11 | 12 | int i, j; 13 | int left, right; 14 | 15 | /* from right to left, find first i for nums[i] < nums[i+1] */ 16 | for (i = numsSize - 2; i >= 0; i--) { 17 | if (nums[i] < nums[i + 1]) break; 18 | } 19 | 20 | /* can't find such i, reverse whole array and return */ 21 | if (i == -1) { 22 | left = 0; 23 | right = numsSize - 1; 24 | for (i = left; i <= left + (right - left) / 2; i++) { 25 | swap(&nums[i], &nums[right - i + left]); 26 | } 27 | return; 28 | } 29 | 30 | /* from right to left, find first j for nums[j] > nums[i] */ 31 | for (j = numsSize - 1; j >= 0; j--) { 32 | if (nums[j] > nums[i]) break; 33 | } 34 | 35 | /* swap nums[i] and nums[j] */ 36 | swap(&nums[i], &nums[j]); 37 | 38 | /* reverse nums[i+1] to nums[n-1] */ 39 | left = i + 1; 40 | right = numsSize - 1; 41 | for (i = left; i <= left + (right - left) / 2; i++) { 42 | swap(&nums[i], &nums[right - i + left]); 43 | } 44 | } 45 | 46 | int main() { 47 | int nums[] = { 1, 2, 3, 4 }; 48 | int size = sizeof(nums) / sizeof(nums[0]); 49 | int i = size; 50 | int count = 1; 51 | while (i) { 52 | count *= i; 53 | i--; 54 | } 55 | 56 | count++; /* test lowest possible order case */ 57 | while (count--){ 58 | for (i = 0; i < size; i++){ 59 | printf("%d ", nums[i]); 60 | } 61 | printf("\n"); 62 | nextPermutation(nums, size); 63 | } 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /src/190.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | https://graphics.stanford.edu/~seander/bithacks.html 6 | */ 7 | 8 | void print_bits(uint32_t n) { 9 | int i = 32; 10 | while(i--){ 11 | if ((n >> i) & 1) 12 | printf("1"); 13 | else 14 | printf("0"); 15 | } 16 | printf("\n"); 17 | } 18 | 19 | /* 32 steps */ 20 | uint32_t reverseBits_1(uint32_t n) { 21 | uint32_t ret = 0; 22 | int i = 31; 23 | while (i--) { // 31 times 24 | ret += n & 0x01; 25 | n >>= 1; 26 | ret <<= 1; 27 | } 28 | ret += n & 0x01; 29 | 30 | return ret; 31 | } 32 | 33 | /* 5 steps : 5 * lg(N) operations */ 34 | uint32_t reverseBits_2(uint32_t n) { 35 | uint32_t t = n; 36 | /* swap odd and even bits 1 bit*/ 37 | t = ((t & 0xAAAAAAAA) >> 1) | ((t & 0x55555555) << 1); 38 | /* 2 bits */ 39 | t = ((t & 0xCCCCCCCC) >> 2) | ((t & 0x33333333) << 2); 40 | /* 4 bits */ 41 | t = ((t & 0xF0F0F0F0) >> 4) | ((t & 0x0F0F0F0F) << 4); 42 | /* 8 bits */ 43 | t = ((t & 0xFF00FF00) >> 8) | ((t & 0x00FF00FF) << 8); 44 | /* 16 bits */ 45 | t = ((t & 0xFFFF0000) >> 16) | ((t & 0x0000FFFF) << 16); 46 | 47 | return t; 48 | } 49 | 50 | /* simplification of reverseBits_2 */ 51 | uint32_t reverseBits(uint32_t n) { 52 | n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1); 53 | n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2); 54 | n = ((n >> 4) & 0x0F0F0F0F) | ((n & 0x0F0F0F0F) << 4); 55 | n = ((n >> 8) & 0x00FF00FF) | ((n & 0x00FF00FF) << 8); 56 | n = ( n >> 16 ) | ( n << 16); 57 | return n; 58 | } 59 | 60 | int main() { 61 | uint32_t n = 2147483648; 62 | printf("%u\n", reverseBits(n)); 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /src/74.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { 7 | bool found = false; 8 | int lr = 0; 9 | int hr = matrixRowSize - 1; 10 | int r = 0; 11 | while (lr <= hr) { 12 | int mr = lr + (hr - lr) / 2; 13 | if (target >= matrix[mr][0] && target <= matrix[mr][matrixColSize - 1]) { 14 | found = true; 15 | r = mr; 16 | break; 17 | } 18 | else if (target < matrix[mr][0]) 19 | hr = mr - 1; 20 | else 21 | lr = mr + 1; 22 | } 23 | 24 | if (found) { 25 | int lc = 0; 26 | int hc = matrixColSize - 1; 27 | 28 | while (lc <= hc) { 29 | int mc = lc + (hc - lc) / 2; 30 | if (matrix[r][mc] == target) 31 | return true; 32 | else if (target < matrix[r][mc]) 33 | hc = mc - 1; 34 | else 35 | lc = mc + 1; 36 | } 37 | 38 | return false; 39 | } 40 | 41 | return false; 42 | } 43 | 44 | int main() { 45 | int rows = 3; 46 | int cols = 4; 47 | 48 | int **matrix = (int **)malloc(rows * sizeof(int *)); 49 | int i; 50 | for (i = 0; i < rows; i++) { 51 | matrix[i] = (int *)malloc(cols * sizeof(int)); 52 | } 53 | 54 | matrix[0][0] = 1; matrix[0][1] = 3; matrix[0][2] = 5; matrix[0][3] = 7; 55 | matrix[1][0] = 10; matrix[1][1] = 11; matrix[1][2] = 16; matrix[1][3] = 20; 56 | matrix[2][0] = 23; matrix[2][1] = 30; matrix[2][2] = 34; matrix[2][3] = 50; 57 | 58 | assert(searchMatrix(matrix, rows, cols, 16) == true); 59 | assert(searchMatrix(matrix, rows, cols, 15) == false); 60 | 61 | printf("all tests passed!\n"); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /src/300.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* Dynamic Programming, O(n*n) */ 6 | int lengthOfLIS0(int* nums, int numsSize) { 7 | if (nums == NULL || numsSize == 0) return 0; 8 | int *dp = (int *)malloc(numsSize * sizeof(int)); 9 | int i, j; 10 | int max = 1; 11 | for (i = 0; i < numsSize; i++) { 12 | int v = 1; /* default value for dp[i] */ 13 | for (j = 0; j < i; j++) { 14 | if (nums[i] > nums[j] && dp[j] + 1 > v) 15 | v = dp[j] + 1; 16 | } 17 | dp[i] = v; 18 | if (v > max) 19 | max = v; 20 | } 21 | free(dp); 22 | return max; 23 | } 24 | 25 | /* Trace the LIS using an array and use binary search, O(nlogn) */ 26 | int lengthOfLIS(int* nums, int numsSize) { 27 | if (nums == NULL || numsSize == 0) return 0; 28 | int *lis = (int *)malloc(numsSize * sizeof(int)); 29 | lis[0] = nums[0]; 30 | int len = 1; 31 | int i; 32 | for (i = 1; i < numsSize; i++) { 33 | if (nums[i] > lis[len - 1]) { 34 | lis[len++] = nums[i]; 35 | } 36 | else { 37 | int l = 0, r = len - 1; 38 | while (l < r) { 39 | int m = l + (r - l) / 2; 40 | if (lis[m] >= nums[i]) { 41 | r = m; 42 | } 43 | else { 44 | l = m + 1; 45 | } 46 | } 47 | lis[l] = nums[i]; 48 | } 49 | } 50 | free(lis); 51 | return len; 52 | } 53 | 54 | int main() { 55 | int nums0[] = { 10, 9, 2, 5, 3, 7, 101, 18 }; 56 | int nums1[] = { 1, 0, 1, 1 }; 57 | assert(lengthOfLIS(nums0, sizeof(nums0) / sizeof(nums0[0])) == 4); 58 | assert(lengthOfLIS(nums1, sizeof(nums1) / sizeof(nums1[0])) == 2); 59 | 60 | printf("all tests passed!\n"); 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /src/132.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int minCut(string s) { 11 | int n = s.length(); 12 | if (n == 0) return 0; 13 | 14 | vector dp(n); 15 | vector > mem(n, vector(n)); // memorization for palindrome 16 | 17 | int i, j, k; 18 | // build palindrome table 19 | for (i = 0; i < n; i++) { 20 | mem[i][i] = 1; 21 | j = i, k = i + 1; // even length 22 | while(j >= 0 && k <= n - 1) { 23 | if (s[j] != s[k]) break; 24 | mem[j][k] = 1; 25 | j--; 26 | k++; 27 | } 28 | j = i - 1, k = i + 1; // odd length 29 | while(j >= 0 && k <= n - 1) { 30 | if (s[j] != s[k]) break; 31 | mem[j][k] = 1; 32 | j--; 33 | k++; 34 | } 35 | } 36 | 37 | // run dynamic programming 38 | dp[0] = 0; 39 | for (i = 1; i < n; i++) { 40 | if (mem[0][i]) { 41 | dp[i] = 0; 42 | } 43 | else { 44 | int min = dp[i - 1] + 1; 45 | for (j = 0; j < i; j++) { 46 | if (mem[j + 1][i] && dp[j] + 1 < min) {// if right half is palindrome 47 | min = dp[j] + 1; 48 | } 49 | } 50 | dp[i] = min; 51 | } 52 | } 53 | 54 | return dp[n - 1]; 55 | } 56 | }; 57 | 58 | int main() { 59 | string str0 = "aababa"; 60 | string str1 = "ababa"; 61 | 62 | Solution s; 63 | 64 | assert(s.minCut(str0) == 1); 65 | assert(s.minCut(str1) == 0); 66 | 67 | printf("all tests passed!\n"); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /src/109.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct ListNode { 7 | int val; 8 | ListNode *next; 9 | ListNode(int x) : val(x), next(NULL) {} 10 | }; 11 | 12 | struct TreeNode { 13 | int val; 14 | TreeNode *left; 15 | TreeNode *right; 16 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 17 | }; 18 | 19 | class Solution { 20 | public: 21 | TreeNode* sortedListToBST(ListNode* head) { 22 | if (head == NULL) return NULL; 23 | 24 | ListNode *fast, *slow, *prev; 25 | fast = slow = head; 26 | prev = NULL; 27 | while (fast) { 28 | fast = fast->next; 29 | if (!fast) break; 30 | fast = fast->next; 31 | prev = slow; 32 | slow = slow->next; 33 | } 34 | 35 | if (slow == NULL) return NULL; 36 | if (prev) prev->next = NULL; 37 | 38 | TreeNode *node = new TreeNode(slow->val); 39 | node->left = sortedListToBST(slow == head ? NULL : head); 40 | node->right = sortedListToBST(slow->next); 41 | 42 | return node; 43 | } 44 | 45 | void preOrderTraversal(TreeNode *root) { 46 | if (root == NULL) return; 47 | 48 | printf("%d ", root->val); 49 | preOrderTraversal(root->left); 50 | preOrderTraversal(root->right); 51 | } 52 | }; 53 | 54 | int main() { 55 | 56 | ListNode *head = new ListNode(1); 57 | ListNode *p = head; 58 | for (int i = 2; i <= 7; i++) { 59 | p->next = new ListNode(i); 60 | p = p->next; 61 | } 62 | p->next = NULL; 63 | 64 | p = head; 65 | while (p) { 66 | printf("%d ", p->val); 67 | p = p->next; 68 | } 69 | printf("\n"); 70 | 71 | Solution s; 72 | TreeNode *root = s.sortedListToBST(head); 73 | 74 | s.preOrderTraversal(root); 75 | printf("\n"); 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /src/72.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int min(int a, int b, int c) { 6 | int min = a; 7 | if (b < min) min = b; 8 | if (c < min) min = c; 9 | return min; 10 | } 11 | 12 | int minDistance(char *word1, char *word2) { 13 | int len1 = strlen(word1); 14 | int len2 = strlen(word2); 15 | 16 | /* these two lines can be commented out */ 17 | if (len1 == 0) return len2; 18 | if (len2 == 0) return len1; 19 | 20 | int(*d)[len2 + 1] = (int (*)[len2 + 1])calloc((len1 + 1) * (len2 + 1), sizeof(int)); 21 | int i, j; 22 | 23 | d[0][0] = 0; /* dummy */ 24 | for (i = 1; i <= len1; i++) d[i][0] = i; 25 | for (j = 1; j <= len2; j++) d[0][j] = j; 26 | 27 | for (i = 1; i <= len1; i++){ 28 | for (j = 1; j <= len2; j++) { 29 | /* d[i][j] represents distance of word1[0..i-1] and word2[0..j-1] */ 30 | if (word1[i - 1] == word2[j - 1]) { 31 | d[i][j] = d[i - 1][j - 1]; 32 | } 33 | else { 34 | d[i][j] = min( 35 | d[i][j - 1] + 1, /* insert a character(word2[j-1]) to the tail of word1[0..i-1] */ 36 | d[i - 1][j] + 1, /* delete a character(word1[i-1]) from the tail of word1[0..i-1] */ 37 | d[i - 1][j - 1] + 1 /* replace a character in tail of word1[0..i-1] */ 38 | ); 39 | } 40 | } 41 | } 42 | return d[len1][len2]; 43 | } 44 | 45 | int main() { 46 | printf("%d %d\n", minDistance("word", "wood"), 1); 47 | printf("%d %d\n", minDistance("word", "woord"), 1); 48 | printf("%d %d\n", minDistance("d", "word"), 3); 49 | printf("%d %d\n", minDistance("", "word"), 4); 50 | printf("%d %d\n", minDistance("abcd", "word"), 3); 51 | printf("%d %d\n", minDistance("ffff", "word"), 4); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /src/82.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* deleteDuplicates(struct ListNode* head) { 10 | if (head == NULL || head->next == NULL) return head; 11 | 12 | struct ListNode *dummy = malloc(sizeof(struct ListNode)); 13 | dummy->val = 0; 14 | dummy->next = head; 15 | struct ListNode *pre = dummy; 16 | struct ListNode *p = dummy->next; 17 | struct ListNode *q = dummy->next->next; 18 | 19 | while (p && q) { 20 | if (p->val == q->val) { 21 | pre->next = q->next; 22 | } 23 | else if (pre->next != q) { 24 | pre = pre->next; 25 | } 26 | p = p->next; 27 | q = q->next; 28 | } 29 | 30 | struct ListNode *new_head = dummy->next; 31 | free(dummy); 32 | 33 | return new_head; 34 | } 35 | 36 | struct ListNode * buildList(int *nums, int numsSize) { 37 | if (numsSize == 0) return NULL; 38 | 39 | struct ListNode *dummy = malloc(sizeof(struct ListNode)); 40 | dummy->val = 0; 41 | struct ListNode *p = dummy; 42 | for (int i = 0; i < numsSize; i++) { 43 | p->next = malloc(sizeof(struct ListNode)); 44 | p->next->val = nums[i]; 45 | p = p->next; 46 | } 47 | p->next = NULL; 48 | 49 | p = dummy->next; 50 | free(dummy); 51 | 52 | return p; 53 | } 54 | 55 | int main() { 56 | 57 | int nums[] = { 1, 2, 2, 2, 3, 3 }; 58 | struct ListNode *head = buildList(nums, sizeof(nums) / sizeof(nums[0])); 59 | struct ListNode *p = head; 60 | while (p) { 61 | printf("%d->", p->val); 62 | p = p->next; 63 | } 64 | printf("NIL\n"); 65 | 66 | struct ListNode *new_head = deleteDuplicates(head); 67 | 68 | p = new_head; 69 | while (p) { 70 | printf("%d->", p->val); 71 | p = p->next; 72 | } 73 | printf("NIL\n"); 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /src/206.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | /* recursive method */ 10 | struct ListNode* reverseList_1(struct ListNode *head) { 11 | if (head == NULL) return NULL; 12 | if (head->next == NULL) return head; 13 | 14 | struct ListNode *new_head, *new_tail; 15 | 16 | new_head = reverseList_1(head->next); 17 | new_tail = head->next; /* new_tail may be NULL here, so we add the second */ 18 | /* if statement. */ 19 | new_tail->next = head; 20 | head->next = NULL; 21 | 22 | return new_head; 23 | } 24 | 25 | /* iterative method */ 26 | struct ListNode* reverseList(struct ListNode* head) { 27 | if (head == NULL) return NULL; 28 | 29 | struct ListNode *prev, *next, *curr; 30 | prev = next = NULL; 31 | curr = head; 32 | while (curr->next) { 33 | next = curr->next; 34 | curr->next = prev; 35 | prev = curr; 36 | curr = next; 37 | } 38 | 39 | curr->next = prev; 40 | return curr; 41 | } 42 | 43 | int main() { 44 | 45 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 46 | 47 | struct ListNode *p = l1; 48 | p->val = 1; 49 | p->next = l1 + 1; 50 | p = p->next; 51 | p->val = 2; 52 | p->next = l1 + 2; 53 | p = p->next; 54 | p->val = 3; 55 | p->next = l1 + 3; 56 | p = p->next; 57 | p->val = 4; 58 | p->next = l1 + 4; 59 | p = p->next; 60 | p->val = 5; 61 | p->next = NULL; 62 | 63 | p = l1; 64 | while (p) { 65 | printf("%d ", p->val); 66 | p = p->next; 67 | } 68 | printf("\n"); 69 | 70 | p = reverseList(l1); 71 | 72 | while (p) { 73 | printf("%d ", p->val); 74 | p = p->next; 75 | } 76 | printf("\n"); 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /src/113.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct TreeNode { 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | vector> pathSum(TreeNode* root, int sum) { 16 | vector > ans; 17 | if (root == NULL) return ans; 18 | 19 | vector path; 20 | pathSumHelper(root, sum, ans, path); 21 | 22 | return ans; 23 | } 24 | 25 | void pathSumHelper(TreeNode *root, int sum, vector > &ans, vector &path) { 26 | if (root == NULL) { 27 | return; 28 | } 29 | if (sum == root->val && root->left == NULL && root->right == NULL) { 30 | path.push_back(root->val); 31 | ans.push_back(path); 32 | path.pop_back(); 33 | return; 34 | } 35 | 36 | path.push_back(root->val); 37 | pathSumHelper(root->left, sum - root->val, ans, path); 38 | pathSumHelper(root->right, sum - root->val, ans, path); 39 | path.pop_back(); 40 | } 41 | }; 42 | 43 | int main() { 44 | int sum = 22; 45 | TreeNode *root = new TreeNode(5); 46 | root->left = new TreeNode(4); 47 | root->right = new TreeNode(8); 48 | 49 | root->left->left = new TreeNode(11); 50 | 51 | root->right->left = new TreeNode(13); 52 | root->right->right = new TreeNode(4); 53 | 54 | root->left->left->left = new TreeNode(7); 55 | root->left->left->right = new TreeNode(2); 56 | 57 | root->right->right->left = new TreeNode(5); 58 | root->right->right->right = new TreeNode(1); 59 | 60 | Solution s; 61 | auto ans = s.pathSum(root, sum); 62 | 63 | for (int i = 0; i < ans.size(); i++) { 64 | for (int j = 0; j < ans[i].size(); j++) { 65 | printf("%d ", ans[i][j]); 66 | } 67 | printf("\n"); 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /src/127.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | int ladderLength(string beginWord, string endWord, unordered_set &wordList) { 13 | queue q; 14 | map visited; 15 | q.push(beginWord); 16 | q.push("LEVEL_END_TAG"); 17 | visited[beginWord] = true; 18 | int level = 1; 19 | while (!q.empty()) { 20 | string word = q.front(); 21 | q.pop(); 22 | if (word != "LEVEL_END_TAG") { 23 | for (int i = 0; i < word.length(); i++) { 24 | string new_word = word; 25 | for (int j = 0; j < 26; j++) { 26 | new_word[i] = j + 'a'; 27 | 28 | if (new_word == endWord) { 29 | level++; 30 | return level; 31 | } 32 | 33 | auto it = wordList.find(new_word); 34 | if (it != wordList.end() && !visited[new_word]) { 35 | q.push(new_word); 36 | visited[new_word] = true; 37 | } 38 | } 39 | } 40 | } 41 | else { 42 | level++; 43 | if (!q.empty()) { 44 | q.push("LEVEL_END_TAG"); 45 | } 46 | } 47 | } 48 | 49 | return 0; 50 | } 51 | }; 52 | 53 | int main() { 54 | unordered_set wordList0 = { "hot", "dot", "dog", "lot", "log" }; 55 | unordered_set wordList1 = { "hot", "dog" } ; 56 | 57 | Solution s; 58 | assert(s.ladderLength("hit", "cog", wordList0) == 5); 59 | assert(s.ladderLength("hot", "dog", wordList1) == 0); 60 | 61 | printf("all tests passed!\n"); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /src/203.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* removeElements(struct ListNode* head, int val) { 10 | struct ListNode *ret; 11 | struct ListNode *prev, *p; 12 | 13 | ret = p = head; 14 | prev = head; 15 | 16 | while (p) { 17 | if (p->val == val) { 18 | if (p == ret) { /* head */ 19 | ret = p->next; 20 | prev = ret; /* maybe useless */ 21 | } 22 | else { /* NOT head */ 23 | prev->next = p->next; 24 | } 25 | } 26 | else { 27 | prev = p; 28 | } 29 | p = p->next; 30 | } 31 | 32 | return ret; 33 | } 34 | 35 | int main() { 36 | struct ListNode *l1 = (struct ListNode *)calloc(9, sizeof(struct ListNode)); 37 | struct ListNode *p = l1; 38 | 39 | p->val = 6; 40 | p->next = l1 + 1; 41 | p = p->next; 42 | 43 | p->val = 6; 44 | p->next = l1 + 2; 45 | p = p->next; 46 | 47 | p->val = 1; 48 | p->next = l1 + 3; 49 | p = p->next; 50 | 51 | p->val = 6; 52 | p->next = l1 + 4; 53 | p = p->next; 54 | 55 | p->val = 6; 56 | p->next = l1 + 5; 57 | p = p->next; 58 | 59 | p->val = 6; 60 | p->next = l1 + 6; 61 | p = p->next; 62 | 63 | p->val = 2; 64 | p->next = l1 + 7; 65 | p = p->next; 66 | 67 | p->val = 3; 68 | p->next = l1 + 8; 69 | p = p->next; 70 | 71 | p->val = 6; 72 | p->next = NULL; 73 | 74 | /* 6 -> 6 -> 1 -> 6 -> 6 -> 6 -> 2 -> 3 -> 6 */ 75 | p = l1; 76 | while (p) { 77 | printf("%d ", p->val); 78 | p = p->next; 79 | } 80 | printf("\n"); 81 | 82 | p = removeElements(l1, 6); 83 | 84 | /* 1 -> 2 -> 3 */ 85 | while (p) { 86 | printf("%d ", p->val); 87 | p = p->next; 88 | } 89 | printf("\n"); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /src/79.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | bool dfs(char** board, int rows, int cols, 7 | bool** visited, int i, int j, 8 | char* word) 9 | { 10 | if (*word == '\0') return true; 11 | 12 | if (i >= 0 && i < rows && j >= 0 && j < cols && !visited[i][j] 13 | && *word == board[i][j] ) 14 | { 15 | visited[i][j] = true; 16 | 17 | bool found = false; 18 | found = dfs(board, rows, cols, visited, i, j - 1, word + 1); /* left */ 19 | if (found) return true; 20 | found = dfs(board, rows, cols, visited, i, j + 1, word + 1); /* right */ 21 | if (found) return true; 22 | found = dfs(board, rows, cols, visited, i - 1, j, word + 1); /* up */ 23 | if (found) return true; 24 | found = dfs(board, rows, cols, visited, i + 1, j, word + 1); /* down */ 25 | if (found) return true; 26 | 27 | visited[i][j] = false; 28 | } 29 | 30 | return false; 31 | } 32 | 33 | bool exist(char** board, int boardRowSize, int boardColSize, char* word) { 34 | if (board == NULL || boardRowSize == 0 || boardColSize == 0 35 | || word == NULL) return false; 36 | 37 | bool **visited = (bool **)calloc(boardRowSize, sizeof(bool *)); 38 | int i, j; 39 | for (i = 0; i < boardRowSize; i++) { 40 | visited[i] = (bool *)calloc(boardColSize, sizeof(bool)); 41 | } 42 | 43 | for (i = 0; i < boardRowSize; i++) { 44 | for (j = 0; j < boardColSize; j++) { 45 | if (board[i][j] == *word) { 46 | bool found = dfs(board, boardRowSize, boardColSize, visited, i, j, word); 47 | if (found) return true; 48 | } 49 | } 50 | } 51 | 52 | return false; 53 | } 54 | 55 | int main() { 56 | char *board[5] = { "aaaa", "aaaa", "aaaa", "aaaa", "aaab" }; 57 | char word[] = "aaaaaaaaaaaaaaaaaaaa"; 58 | 59 | assert(exist(board, 5, 4, word) == false); 60 | 61 | printf("all tests passed!\n"); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /src/20.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef int bool; 6 | #define true 1 7 | #define false 0 8 | 9 | struct Node { 10 | char val; 11 | struct Node *next; 12 | }; 13 | 14 | void push(struct Node** top_pt, char new_data) 15 | { 16 | struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); 17 | new_node->val = new_data; 18 | new_node->next = *top_pt; 19 | 20 | *top_pt = new_node; 21 | } 22 | 23 | int pop(struct Node** top_pt) 24 | { 25 | if (*top_pt == NULL) 26 | { 27 | printf("stack overflow\n"); 28 | exit(0); 29 | } 30 | struct Node *top = *top_pt; 31 | char res = top->val; 32 | *top_pt = top->next; 33 | free(top); 34 | return res; 35 | } 36 | 37 | bool isValid(char *s) { 38 | struct Node *stack = NULL; 39 | int i; 40 | int len = strlen(s); 41 | for (i = 0; i < len; i++) { 42 | if (s[i] == '(' || s[i] == '[' || s[i] == '{') { 43 | push(&stack, s[i]); 44 | } 45 | else { 46 | if (stack == NULL) 47 | return false; 48 | char top = pop(&stack); 49 | if (s[i] == ')') { 50 | if (top != '(') return false; 51 | } 52 | else if (s[i] == ']'){ 53 | if (top != '[') return false; 54 | } 55 | else if (s[i] == '}'){ 56 | if (top != '{') return false; 57 | } 58 | } 59 | } 60 | if (stack == NULL) 61 | return true; 62 | else 63 | return false; 64 | } 65 | 66 | void print_stack(struct Node** top_pt) 67 | { 68 | struct Node *t = *top_pt; 69 | while (t != NULL) 70 | { 71 | struct Node *tmp_node = t; 72 | printf("%c ", tmp_node->val); 73 | t = tmp_node->next; 74 | } 75 | printf("\n"); 76 | } 77 | 78 | int main() 79 | { 80 | char s[] = "]"; 81 | printf("%d\n", isValid(s)); 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /src/201.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int rangeBitwiseAnd_1(int m, int n) { 5 | unsigned ans = m; 6 | unsigned k; 7 | unsigned one_index = 0; /* first one's index */ 8 | unsigned zero_index = 0; /* first zero after the first one */ 9 | 10 | while (one_index < 31) { 11 | while (one_index < 31 && (ans & (1 << one_index)) == 0){ 12 | one_index ++; 13 | } 14 | 15 | zero_index = one_index; 16 | while (zero_index < 32 && ans & (1 << zero_index)) { 17 | zero_index ++; 18 | } 19 | 20 | if (zero_index > one_index) { 21 | /* nearest number to make first one to zero */ 22 | k = (ans | (1 << zero_index)) >> zero_index; 23 | k = k << zero_index; 24 | 25 | if (k > n) return ans; /* rest numbers are useless */ 26 | ans &= k; 27 | } 28 | 29 | if (ans == 0) return 0; /* it's pointless to continue looping */ 30 | one_index ++; 31 | } 32 | 33 | return ans; 34 | } 35 | 36 | /** 37 | * algorithm comes from http://math.stackexchange.com/a/1073544 38 | */ 39 | int rangeBitwiseAnd(int m, int n) { 40 | int k = 30; 41 | unsigned ans = m & n; 42 | /* check kth bit, if they are different, set remain bits to zero */ 43 | while (k > 0 && (m & (1 << k)) == (n & (1 << k))){ 44 | k--; 45 | } 46 | /* there is no need to check 0th bit, we already do m AND n*/ 47 | ans >>= k; 48 | ans <<= k; 49 | return ans; 50 | } 51 | 52 | int main() { 53 | /* should be 0 */ 54 | printf("%d\n", rangeBitwiseAnd(2, 4)); 55 | 56 | /* should be 2147483644 */ 57 | printf("%d\n", rangeBitwiseAnd(2147483645, 2147483647)); 58 | 59 | /* should be 2147483647 */ 60 | printf("%d\n", rangeBitwiseAnd(2147483647, 2147483647)); 61 | 62 | /* should be 0 */ 63 | printf("%d\n", rangeBitwiseAnd(700000000, 2147483641)); 64 | 65 | /* should be 0 */ 66 | printf("%d\n", rangeBitwiseAnd(3, 4)); 67 | 68 | return 0; 69 | } -------------------------------------------------------------------------------- /src/90.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /* code is similar as https://leetcode.com/problems/subsets/ */ 7 | class Solution { 8 | public: 9 | vector> subsetsWithDup(vector& nums) { 10 | unsigned int n = nums.size(); 11 | vector> ans; 12 | if (n == 0) return ans; 13 | 14 | quicksort(nums, 0, n - 1); 15 | 16 | vector temp; 17 | for (unsigned int i = 0; i < (1 << n); i++) { 18 | unsigned int t = i; 19 | unsigned int k = 0; 20 | while (t) { 21 | if (t & 1) { 22 | temp.push_back(nums[k]); 23 | } 24 | t >>= 1; 25 | k++; 26 | } 27 | 28 | bool found = false; 29 | for (int j = 0; j < ans.size(); j++) { 30 | if (temp == ans[j]) { 31 | found = true; 32 | break; 33 | } 34 | } 35 | 36 | if (!found) 37 | ans.push_back(temp); 38 | temp.clear(); 39 | } 40 | 41 | return ans; 42 | } 43 | 44 | void quicksort(vector &nums, int start, int end) { 45 | if (start >= end) return; 46 | int i = start; 47 | int j = end; 48 | int sentinal = nums[start]; 49 | while (i < j) { 50 | while (i < j && nums[j] >= sentinal) 51 | j--; 52 | 53 | nums[i] = nums[j]; 54 | while (i < j && nums[i] <= sentinal) 55 | i++; 56 | 57 | nums[j] = nums[i]; 58 | } 59 | 60 | nums[i] = sentinal; 61 | 62 | quicksort(nums, start, i - 1); 63 | quicksort(nums, i + 1, end); 64 | } 65 | }; 66 | 67 | int main() { 68 | vector nums = {2, 2, 1}; 69 | Solution s; 70 | auto ans = s.subsetsWithDup(nums); 71 | for (int i = 0; i < ans.size(); i++) { 72 | for (int j = 0 ; j < ans[i].size(); j++) { 73 | printf("%d ", ans[i][j]); 74 | } 75 | printf("\n"); 76 | } 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /src/40.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector> combinationSum2(vector& candidates, int target) { 10 | vector > ans; 11 | vector flag(candidates.size(), false); 12 | vector temp; 13 | 14 | combinationSum2Helper(ans, flag, temp, candidates, target); 15 | 16 | return ans; 17 | } 18 | 19 | /* Very slow, 424 ms. Need to improved. */ 20 | void combinationSum2Helper(vector > &ans, vector &flag, vector &temp, vector &candidates, int target) { 21 | if (target == 0) { 22 | bool found = false; 23 | for (vector >::iterator it = ans.begin(); it != ans.end(); it++) { 24 | if (temp == *it) { 25 | found = true; 26 | break; 27 | } 28 | } 29 | if (!found) 30 | ans.push_back(temp); 31 | 32 | return; 33 | } 34 | else if (target < 0) { 35 | return; 36 | } 37 | 38 | int max = 0; 39 | for (int k = 0; k < temp.size(); k++) { 40 | if (temp[k] > max) 41 | max = temp[k]; 42 | } 43 | 44 | for (int i = 0; i < candidates.size(); i++) { 45 | if (!flag[i] && candidates[i] >= max) { 46 | flag[i] = true; 47 | temp.push_back(candidates[i]); 48 | combinationSum2Helper(ans, flag, temp, candidates, target - candidates[i]); 49 | temp.pop_back(); 50 | flag[i] = false; 51 | } 52 | } 53 | } 54 | }; 55 | 56 | int main() { 57 | vector candidates = {10, 1, 2, 7, 6, 1, 5}; 58 | int target = 8; 59 | Solution s; 60 | vector > ans = s.combinationSum2(candidates, target); 61 | 62 | for (int i = 0; i < ans.size(); i++) { 63 | for (int j = 0; j < ans[i].size(); j++) { 64 | printf("%d ", ans[i][j]); 65 | } 66 | printf("\n"); 67 | } 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /src/150.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct Node { 6 | int val; 7 | struct Node *next; 8 | }; 9 | 10 | void push(struct Node** top_pt, int new_data) 11 | { 12 | struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); 13 | new_node->val = new_data; 14 | new_node->next = *top_pt; 15 | 16 | *top_pt = new_node; 17 | } 18 | 19 | int pop(struct Node** top_pt) 20 | { 21 | if (*top_pt == NULL) 22 | { 23 | printf("stack overflow\n"); 24 | exit(0); 25 | } 26 | struct Node *top = *top_pt; 27 | int res = top->val; 28 | *top_pt = top->next; 29 | free(top); 30 | return res; 31 | } 32 | 33 | int evalRPN(char *tokens[], int n) { 34 | struct Node *stack = NULL; 35 | int i; 36 | for (i = 0; i < n; i++) 37 | { 38 | if (strcmp(tokens[i], "+") == 0) { 39 | int r = pop(&stack); 40 | int l = pop(&stack); 41 | push(&stack, l + r); 42 | } 43 | else if (strcmp(tokens[i], "-") == 0) { 44 | int r = pop(&stack); 45 | int l = pop(&stack); 46 | push(&stack, l - r); 47 | } 48 | else if (strcmp(tokens[i], "*") == 0) { 49 | int r = pop(&stack); 50 | int l = pop(&stack); 51 | push(&stack, l * r); 52 | } 53 | else if (strcmp(tokens[i], "/") == 0) { 54 | int r = pop(&stack); 55 | int l = pop(&stack); 56 | push(&stack, l / r); 57 | } 58 | else 59 | push(&stack, atoi(tokens[i])); 60 | } 61 | return pop(&stack); 62 | } 63 | 64 | void print_stack(struct Node** top_pt) 65 | { 66 | struct Node *t = *top_pt; 67 | while (t != NULL) 68 | { 69 | struct Node *tmp_node = t; 70 | printf("%d ", tmp_node->val); 71 | t = tmp_node->next; 72 | } 73 | printf("\n"); 74 | } 75 | 76 | int main() 77 | { 78 | char *tokens[] = {"3","-4","+"}; 79 | printf("%d\n", evalRPN(tokens, sizeof(tokens)/ sizeof(tokens[0]))); 80 | return 0; 81 | } 82 | 83 | -------------------------------------------------------------------------------- /src/283.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) { 4 | int c = *a; 5 | *a = *b; 6 | *b = c; 7 | } 8 | 9 | /* Bubble sort, O(n*n) */ 10 | void moveZeroes0(int* nums, int numsSize) { 11 | int i, j; 12 | for (i = numsSize - 1; i >= 0; i--) { 13 | for (j = 0; j < i; j++) { 14 | if (nums[j] == 0 && nums[j + 1] != 0) { 15 | swap(&nums[j], &nums[j + 1]); 16 | } 17 | } 18 | } 19 | } 20 | 21 | /* Divide and conquer, T(n) = 2T(n/2) + O(3n) = O(nlogn) */ 22 | void moveZeroes1(int* nums, int numsSize) { 23 | if (numsSize <= 1 ) return; 24 | if (numsSize == 2) { 25 | if (nums[0] == 0 && nums[1] != 0) { 26 | swap(&nums[0], &nums[1]); 27 | } 28 | return; 29 | } 30 | 31 | int mid = numsSize / 2; 32 | 33 | moveZeroes1(nums, mid); 34 | moveZeroes1(nums + mid, numsSize - mid); 35 | 36 | int left = 0, right = numsSize - 1; 37 | while (nums[left] != 0) left++; 38 | while (nums[right] == 0) right--; 39 | 40 | if (right <= left) return; 41 | 42 | int i; 43 | for (i = left; i <= left + (mid - 1 - left) / 2 ; i++) { 44 | swap(&nums[i], &nums[mid - 1 - i + left]); 45 | } 46 | 47 | for (i = mid; i <= mid + (right - mid - 1) / 2; i++) { 48 | swap(&nums[i], &nums[right - i + mid]); 49 | } 50 | 51 | for (i = left; i <= left + (right - left) / 2; i++) { 52 | swap(&nums[i], &nums[right - i + left]); 53 | } 54 | } 55 | 56 | /* fill zeroes into positions, O(n) */ 57 | void moveZeroes(int* nums, int numsSize) { 58 | int storeIndex = 0; 59 | int i = 0; 60 | for (i = 0; i < numsSize; i++) { 61 | if (nums[i] != 0) { 62 | nums[storeIndex++] = nums[i]; 63 | } 64 | } 65 | 66 | for (i = storeIndex; i < numsSize; i++) { 67 | nums[i] = 0; 68 | } 69 | } 70 | 71 | int main() { 72 | int nums[] = { 0, 1, 0, 3, 12 }; 73 | int size = sizeof(nums) / sizeof(nums[0]); 74 | 75 | moveZeroes(nums, size); 76 | 77 | int i; 78 | for (i = 0; i < size; i++) { 79 | printf("%d ", nums[i]); 80 | } 81 | printf("\n"); 82 | 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /src/236.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct TreeNode { 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 16 | if (root == NULL) return NULL; 17 | 18 | vector path_p; 19 | vector path_q; 20 | 21 | dfs(root, p, path_p); 22 | dfs(root, q, path_q); 23 | 24 | int minLen = min(path_p.size(), path_q.size()); 25 | TreeNode *lca = NULL; 26 | 27 | for (int i = 0; i < minLen; i++) { 28 | if (path_p[i] != path_q[i]) { 29 | break; 30 | } 31 | lca = path_p[i]; 32 | } 33 | 34 | return lca; 35 | } 36 | 37 | bool dfs(TreeNode *root, TreeNode *t, vector &path) { 38 | if (root == NULL || t == NULL) return false; 39 | 40 | if (root == t) { 41 | path.push_back(root); 42 | return true; 43 | } 44 | 45 | path.push_back(root); 46 | 47 | if (dfs(root->left, t, path)) return true; 48 | if (dfs(root->right, t, path)) return true; 49 | 50 | path.pop_back(); 51 | 52 | return false; 53 | } 54 | }; 55 | 56 | int main() { 57 | TreeNode *root = new TreeNode(3); 58 | root->left = new TreeNode(5); 59 | root->right = new TreeNode(1); 60 | 61 | TreeNode *p = root->left; 62 | TreeNode *q = root->right; 63 | 64 | root->left->left = new TreeNode(6); 65 | root->left->right = new TreeNode(2); 66 | root->left->right->left = new TreeNode(7); 67 | root->left->right->right = new TreeNode(4); 68 | 69 | root->right->left = new TreeNode(0); 70 | root->right->right = new TreeNode(8); 71 | 72 | Solution s; 73 | TreeNode *ans = s.lowestCommonAncestor(root, p, q); 74 | 75 | printf("p: %d\nq: %d\n", p->val, q->val); 76 | if (ans) { 77 | printf("lca: %d\n", ans->val); 78 | } 79 | else { 80 | printf("lca: NIL\n"); 81 | } 82 | 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /src/275.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | static inline int min(int a, int b) { 5 | return (a < b) ? a : b; 6 | } 7 | 8 | /* from current position to the end, we can caculate an hIndex array 9 | the hIndex will first ascend and then descend 10 | so the problem is to find the peak of the hIndex array 11 | we use binary search */ 12 | 13 | int hIndex(int* citations, int citationsSize) { 14 | if (citations == NULL || citationsSize == 0) return 0; 15 | 16 | if (citationsSize == 1) return min(citations[0], 1); 17 | 18 | int i = 0, j = citationsSize - 1; 19 | int h_prev, h_middle, h_next; 20 | 21 | while (i <= j) { 22 | int m = i + (j - i) / 2; 23 | h_prev = min(citations[m - 1], citationsSize - m + 1); 24 | h_middle = min(citations[m], citationsSize - m); 25 | h_next = min(citations[m + 1], citationsSize - m - 1); 26 | if (h_prev <= h_middle && h_middle > h_next) { 27 | break; 28 | } 29 | else if (h_middle <= h_next) { 30 | i = m + 1; 31 | } 32 | else if (h_middle > h_next) { 33 | j = m - 1; 34 | } 35 | else { 36 | i++; 37 | } 38 | } 39 | 40 | return h_middle; 41 | } 42 | 43 | int hIndex0(int* citations, int citationsSize) { 44 | if (citations == NULL || citationsSize == 0) return 0; 45 | 46 | int i = 0, j = citationsSize - 1; 47 | while (i <= j) { 48 | int m = i + (j - i) / 2; 49 | if (citations[m] >= citationsSize - m) { 50 | j = m - 1; 51 | } 52 | else { 53 | i = m + 1; 54 | } 55 | } 56 | 57 | return citationsSize - i; 58 | } 59 | 60 | int main() { 61 | 62 | int citations0[] = { 0, 1, 3, 5, 6 }; 63 | int citations1[] = { 0, 3, 3, 3, 4 }; 64 | int citations2[] = { 0, 3, 4, 4, 4, 4, 5, 5 }; 65 | 66 | assert(hIndex(citations0, sizeof(citations0) / sizeof(citations0[0])) == 3); 67 | assert(hIndex(citations1, sizeof(citations1) / sizeof(citations1[0])) == 3); 68 | assert(hIndex(citations2, sizeof(citations2) / sizeof(citations2[0])) == 4); 69 | 70 | printf("all tests passed!\n"); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /src/75.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) { 4 | int c = *a; 5 | *a = *b; 6 | *b = c; 7 | } 8 | 9 | /* Dutch national flag problem. 10 | * three way partition, just like radix sort 11 | */ 12 | void sortColors(int* nums, int numsSize) { 13 | int i, zero, two; 14 | i = 0; 15 | zero = 0; 16 | two = numsSize - 1; 17 | 18 | while (i <= two) { 19 | if (nums[i] == 0) { 20 | swap(&nums[i], &nums[zero++]); 21 | i++; /* index i scans from left to right, so we don't need to check 22 | * if left side have 2, just swap and move forward. 23 | * And, if the numbers are all 0, we must move forward, 24 | * otherwise we will loop forever. 25 | */ 26 | } 27 | else if (nums[i] == 2) { 28 | swap(&nums[i], &nums[two--]); 29 | /* right side may have 0, so we stop at this position and check 30 | * repeatedly. the loop will exit if pointer two is smaller than i. 31 | */ 32 | } 33 | else { 34 | i++; 35 | } 36 | } 37 | } 38 | 39 | /* simply fill the numbers, O(n), two-pass */ 40 | void sortColors0(int* nums, int numsSize) { 41 | int i, zero_count, one_count; 42 | zero_count = 0; 43 | one_count = 0; 44 | 45 | for (i = 0; i < numsSize; i++) { 46 | if (nums[i] == 0) { 47 | zero_count++; 48 | } 49 | if (nums[i] == 1) { 50 | one_count++; 51 | } 52 | } 53 | 54 | for (i = 0; i < zero_count; i++) { 55 | nums[i] = 0; 56 | } 57 | 58 | for (i = zero_count; i < zero_count + one_count; i++) { 59 | nums[i] = 1; 60 | } 61 | 62 | for ( ; i < numsSize; i++) { 63 | nums[i] = 2; 64 | } 65 | } 66 | 67 | int main() { 68 | int nums[] = { 1, 2, 0, 1, 0, 2, 0, 0, 1, 0, 2, 1 }; 69 | int size = sizeof(nums) / sizeof(nums[0]); 70 | sortColors(nums, size); 71 | int i; 72 | for (i = 0; i < size; i++) { 73 | printf("%d ", nums[i]); 74 | } 75 | printf("\n"); 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /src/12.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char *intToRoman(int num) { 5 | char *s = (char *)calloc(10, sizeof(char)); 6 | int i = 0; 7 | while (num > 0) { 8 | while (num >= 1000) { 9 | s[i] = 'M'; 10 | num -= 1000; 11 | i++; 12 | } 13 | if (num >= 900) { 14 | s[i] = 'C'; s[i + 1] = 'M'; 15 | i += 2; 16 | num -= 900; 17 | } 18 | while (num >= 500) { 19 | s[i] = 'D'; 20 | num -= 500; 21 | i++; 22 | } 23 | if (num >= 400) { 24 | s[i] = 'C'; s[i + 1] = 'D'; 25 | i += 2; 26 | num -= 400; 27 | } 28 | while (num >= 100) { 29 | s[i] = 'C'; 30 | num -= 100; 31 | i++; 32 | } 33 | if (num >= 90) { 34 | s[i] = 'X'; s[i + 1] = 'C'; 35 | i += 2; 36 | num -= 90; 37 | } 38 | while (num >= 50) { 39 | s[i] = 'L'; 40 | num -= 50; 41 | i++; 42 | } 43 | if (num >= 40) { 44 | s[i] = 'X'; s[i + 1] = 'L'; 45 | i += 2; 46 | num -= 40; 47 | } 48 | while (num >= 10) { 49 | s[i] = 'X'; 50 | num -= 10; 51 | i++; 52 | } 53 | if (num >= 9) { 54 | s[i] = 'I'; s[i + 1] = 'X'; 55 | i += 2; 56 | num -= 9; 57 | } 58 | while (num >= 5) { 59 | s[i] = 'V'; 60 | num -= 5; 61 | i++; 62 | } 63 | if (num >= 4) { 64 | s[i] = 'I'; s[i + 1] = 'V'; 65 | i += 2; 66 | num -= 4; 67 | } 68 | while (num >= 1) { 69 | s[i] = 'I'; 70 | num -= 1; 71 | i++; 72 | } 73 | } 74 | return s; 75 | } 76 | 77 | int main() { 78 | int a = 2014; 79 | int b = 2015; 80 | /* should be MMXIV */ 81 | printf("%s\n", intToRoman(a)); 82 | /* should be MMXV */ 83 | printf("%s\n", intToRoman(b)); 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /src/110.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct TreeNode { 6 | int val; 7 | struct TreeNode *left; 8 | struct TreeNode *right; 9 | }; 10 | 11 | int maxDepth(struct TreeNode *root) { 12 | if (root == NULL) 13 | return 0; 14 | int l = maxDepth(root->left); 15 | int r = maxDepth(root->right); 16 | if (l > r) 17 | return l + 1; 18 | else 19 | return r + 1; 20 | } 21 | 22 | bool isBalanced(struct TreeNode *root) { 23 | if (root == NULL) 24 | return true; 25 | 26 | int l = maxDepth(root->left); 27 | int r = maxDepth(root->right); 28 | int d = l - r; 29 | if (d == 0 || d == 1 || d == -1) { 30 | if (isBalanced(root->left) && isBalanced(root->right)) { 31 | return true; 32 | } 33 | else return false; 34 | } 35 | else return false; 36 | } 37 | 38 | void printTreePreOrder(struct TreeNode *p) { 39 | if (p != NULL) { 40 | printf("%d", p->val); 41 | printTreePreOrder(p->left); 42 | printTreePreOrder(p->right); 43 | } 44 | else printf("#"); 45 | } 46 | 47 | int main() { 48 | struct TreeNode *t = (struct TreeNode *)calloc(7, sizeof(struct TreeNode)); 49 | struct TreeNode *p = t; 50 | p->val = 1; 51 | 52 | p->left = ++t; 53 | t->val = 2; 54 | p->left->left = ++t; 55 | p->left->right = NULL; 56 | t->val = 3; 57 | p->left->left->left = ++t; 58 | p->left->left->right = NULL; 59 | t->val = 4; 60 | t->left = t->right = NULL; 61 | 62 | p->right = ++t; 63 | t->val = 2; 64 | p->right->left = NULL; 65 | p->right->right = ++t; 66 | t->val = 3; 67 | p->right->right->left = NULL; 68 | p->right->right->right = ++t; 69 | t->val = 4; 70 | t->left = t->right = NULL; 71 | 72 | printTreePreOrder(p); printf("\n"); 73 | 74 | printf("%d\n", isBalanced(p)); /* should be false */ 75 | printf("%d\n", isBalanced(p->left)); /* should be false */ 76 | printf("%d\n", isBalanced(p->left->left)); /* should be true */ 77 | printf("%d\n", isBalanced(NULL)); /* should be true */ 78 | 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /src/235.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | struct TreeNode *left; 7 | struct TreeNode *right; 8 | }; 9 | 10 | struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { 11 | if (root == NULL) return NULL; 12 | 13 | if (p == NULL) return q; 14 | if (q == NULL) return p; 15 | 16 | struct TreeNode *i, *j, *lca; 17 | i = j = lca = root; 18 | 19 | while (i || j) { 20 | if (i->val > p->val) { 21 | i = i->left; 22 | } 23 | else if (i->val < p->val) { 24 | i = i->right; 25 | } 26 | else { 27 | lca = i; 28 | break; 29 | } 30 | 31 | if (j->val > q->val) { 32 | j = j->left; 33 | } 34 | else if (j->val < q->val) { 35 | j = j->right; 36 | } 37 | else { 38 | lca = j; 39 | break; 40 | } 41 | 42 | 43 | if (i->val != j->val) { 44 | break; 45 | } 46 | lca = i; 47 | } 48 | 49 | return lca; 50 | } 51 | 52 | int main() { 53 | 54 | struct TreeNode *r = (struct TreeNode *)calloc(9, sizeof(struct TreeNode)); 55 | struct TreeNode *t = r; 56 | struct TreeNode *p = NULL, *q = NULL; 57 | 58 | t->val = 6; 59 | t->left = r + 1; 60 | t->right = r + 2; 61 | 62 | t = t->left; 63 | t->val = 2; 64 | t->left = r + 3; 65 | t->right = r + 4; 66 | t->left->val = 0; 67 | 68 | t = r + 4; 69 | t->val = 4; 70 | t->left = r + 5; 71 | t->right = r + 6; 72 | t->left->val = 3; 73 | t->right->val = 5; 74 | 75 | t = r->right; 76 | t->val = 8; 77 | t->left = r + 7; 78 | t->right = r + 8; 79 | t->left->val = 7; 80 | t->right->val = 9; 81 | 82 | p = r + 1; /* 2 */ 83 | q = r + 2; /* 8 */ 84 | 85 | struct TreeNode *lca = lowestCommonAncestor(r, p, q); 86 | 87 | printf("lca of %d and %d is: %d\n", p->val, q->val, lca->val); 88 | 89 | p = r + 1; /* 2 */ 90 | q = r + 4; /* 4 */ 91 | 92 | lca = lowestCommonAncestor(r, p, q); 93 | 94 | printf("lca of %d and %d is: %d\n", p->val, q->val, lca->val); 95 | 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /src/165.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* 6 | int compareVersion(char *version1, char *version2){ 7 | #define MAX 1024 8 | int v1[MAX] = {0}; 9 | int v2[MAX] = {0}; 10 | char *pch = strtok(version1, "."); 11 | int i = 0; 12 | while (pch != NULL) { 13 | v1[i] = atoi(pch); 14 | pch = strtok(NULL, "."); 15 | i++; 16 | } 17 | 18 | pch = strtok(version2, "."); 19 | i = 0; 20 | while (pch != NULL) { 21 | v2[i] = atoi(pch); 22 | pch = strtok(NULL, "."); 23 | i++; 24 | } 25 | for (i = 0; i < MAX; i++) { 26 | if (v1[i] > v2[i]) return 1; 27 | else if (v1[i] < v2[i]) return -1; 28 | } 29 | return 0; 30 | } 31 | */ 32 | 33 | int compareVersion(char *version1, char *version2){ 34 | int i, j, v1, v2, len1, len2; 35 | i = j = v1 = v2 = 0; 36 | len1 = strlen(version1); 37 | len2 = strlen(version2); 38 | 39 | while (i < len1 || j < len2) { 40 | while (i < len1 && version1[i] != '.') { 41 | v1 = v1 * 10 + (version1[i] - '0'); 42 | i++; 43 | } 44 | while (j < len2 && version2[j] != '.') { 45 | v2 = v2 * 10 + (version2[j] - '0'); 46 | j++; 47 | } 48 | if (v1 > v2) return 1; 49 | else if (v1 < v2) return -1; 50 | else { 51 | v1 = v2 = 0; 52 | i++; 53 | j++; 54 | } 55 | } 56 | return 0; 57 | } 58 | 59 | int main() { 60 | char v1[] = "19.8.3.17.5.01.0.0.4.0.0.0.0.0.0.0.0.0.0.0.0.0.00.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.000000.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.000000"; 61 | char v2[] = "19.8.3.17.5.01.0.0.4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0000.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.000000"; 62 | 63 | printf("%d\n", compareVersion(v1, v2)); 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /src/92.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode *reverseBetween(struct ListNode *head, int m, int n) { 10 | struct ListNode *front, *rear; /* front and rear node of reversed list */ 11 | struct ListNode *left, *right; /* left and right linked point */ 12 | struct ListNode *p, *q, *t; 13 | front = rear = left = right = NULL; 14 | 15 | int len = n - m + 1; 16 | t = head; 17 | m -= 1; 18 | while (m--) { 19 | left = t; 20 | t = t->next; 21 | } 22 | 23 | rear = t; 24 | p = q = NULL; 25 | while (len--) { 26 | q = t->next; 27 | t->next = p; 28 | p = t; 29 | t = q; 30 | } 31 | right = t; 32 | front = p; 33 | 34 | /* left to front, rear to right */ 35 | if (left) { 36 | left->next = front; 37 | } 38 | else { 39 | head = front; 40 | } 41 | rear->next = right; 42 | 43 | return head; 44 | } 45 | 46 | int main() { 47 | struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 48 | struct ListNode *p = l1; 49 | 50 | int i; 51 | for (i = 1; i <= 4; i++) { 52 | p->val = i; 53 | p->next = p + 1; 54 | p++; 55 | } 56 | p->val = 5; 57 | p->next = NULL; 58 | 59 | p = l1; 60 | while (p) { 61 | printf("%d ", p->val); 62 | p = p->next; 63 | } 64 | printf("\n"); 65 | 66 | p = reverseBetween(l1, 2, 4); 67 | while (p) { 68 | printf("%d ", p->val); 69 | p = p->next; 70 | } 71 | printf("\n"); 72 | 73 | struct ListNode *l2 = (struct ListNode *)calloc(2, sizeof(struct ListNode)); 74 | l2->val = 3; 75 | l2->next = l2 + 1; 76 | l2->next->val = 5; 77 | l2->next->next = NULL; 78 | 79 | p = l2; 80 | while (p) { 81 | printf("%d ", p->val); 82 | p = p->next; 83 | } 84 | printf("\n"); 85 | 86 | p = reverseBetween(l2, 1, 2); 87 | while (p) { 88 | printf("%d ", p->val); 89 | p = p->next; 90 | } 91 | printf("\n"); 92 | 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /src/17.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector letterCombinations(string digits) { 10 | vector ans; 11 | int len = digits.length(); 12 | if (len == 0) return ans; 13 | 14 | vector letters(len); 15 | string temp; 16 | 17 | for (int i = 0; i < digits.length(); i++) { 18 | switch(digits[i]) { 19 | case '2': 20 | letters[i] = "abc"; 21 | break; 22 | case '3': 23 | letters[i] = "def"; 24 | break; 25 | case '4': 26 | letters[i] = "ghi"; 27 | break; 28 | case '5': 29 | letters[i] = "jkl"; 30 | break; 31 | case '6': 32 | letters[i] = "mno"; 33 | break; 34 | case '7': 35 | letters[i] = "pqrs"; 36 | break; 37 | case '8': 38 | letters[i] = "tuv"; 39 | break; 40 | case '9': 41 | letters[i] = "wxyz"; 42 | break; 43 | default: 44 | break; 45 | } 46 | } 47 | 48 | letterCombinationsHelper(ans, temp, 0, letters); 49 | 50 | return ans; 51 | } 52 | 53 | void letterCombinationsHelper(vector &ans, string &temp, int depth, vector letters) { 54 | if (depth == letters.size()) { 55 | ans.push_back(temp); 56 | return; 57 | } 58 | 59 | for (int j = 0; j < letters[depth].size(); j++) { 60 | temp.push_back(letters[depth][j]); 61 | letterCombinationsHelper(ans, temp, depth + 1, letters); 62 | temp.pop_back(); 63 | } 64 | } 65 | }; 66 | 67 | int main() { 68 | string digits = "23"; 69 | Solution s; 70 | vector ans = s.letterCombinations(digits); 71 | 72 | for (int i = 0; i < ans.size(); i++) { 73 | cout << ans[i] << endl; 74 | } 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /src/107.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct TreeNode { 9 | int val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | }; 14 | 15 | class Solution { 16 | public: 17 | vector > levelOrderBottom(TreeNode *root) { 18 | vector > ret; 19 | vector t; 20 | queue q; 21 | if (!root) return ret; 22 | q.push(root); 23 | 24 | int next = 0; // number of nodes in next level, includling NULL nodes 25 | int cur = 1; // number of nodes in current level, including NULL nodes 26 | int count = 0; // count of nodes already traversed in current level 27 | while (!q.empty()) { 28 | TreeNode *p = q.front(); 29 | q.pop(); 30 | 31 | if (p){// push children into queue if parent is not NULL 32 | t.push_back(p->val); 33 | q.push(p->left); 34 | q.push(p->right); 35 | next += 2; 36 | } 37 | 38 | count++; 39 | if (count == cur && !t.empty()) { 40 | ret.push_back(t); 41 | t.clear(); 42 | cur = next; 43 | count = next = 0; 44 | } 45 | } 46 | 47 | reverse(ret.begin(), ret.end()); //reverse result vector 48 | return ret; 49 | } 50 | }; 51 | 52 | int main() { 53 | TreeNode *root = new TreeNode(1); 54 | TreeNode *p = root; 55 | p->left = new TreeNode(2); 56 | p->right = new TreeNode(3); 57 | p = p->right; 58 | p->left = new TreeNode(4); 59 | p = p->left; 60 | p->right = new TreeNode(5); 61 | p = p->right; 62 | p->left = new TreeNode(6); 63 | p->right = new TreeNode(7); 64 | 65 | Solution s; 66 | vector > ret = s.levelOrderBottom(root); 67 | 68 | for (int i = 0; i < ret.size(); i++) { 69 | for (int j = 0; j < ret[i].size(); j++) { 70 | cout << ret[i][j]; 71 | } 72 | cout << endl; 73 | } 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /src/133.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct UndirectedGraphNode { 8 | int label; 9 | vector neighbors; 10 | UndirectedGraphNode(int x) : label(x) {}; 11 | }; 12 | 13 | class Solution { 14 | map copyMap; 15 | public: 16 | UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 17 | if (node == NULL) return NULL; 18 | return dfs(node); 19 | } 20 | 21 | UndirectedGraphNode* dfs(UndirectedGraphNode *node) { 22 | UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label); 23 | copyMap[node] = new_node; 24 | for (auto u : node->neighbors) { 25 | if (copyMap[u]) { 26 | new_node->neighbors.push_back(copyMap[u]); 27 | } 28 | else { 29 | new_node->neighbors.push_back(dfs(u)); 30 | } 31 | } 32 | return new_node; 33 | } 34 | 35 | void printGraph(UndirectedGraphNode *node) { 36 | map visited; 37 | printHelper(visited, node); 38 | printf("\n"); 39 | } 40 | 41 | void printHelper(map &visited, UndirectedGraphNode *node) { 42 | if (node == NULL) return; 43 | if (visited[node]) return; 44 | 45 | printf("%d", node->label); 46 | for (auto u : node->neighbors) { 47 | printf(",%d", u->label); 48 | } 49 | printf("#"); 50 | visited[node] = true; 51 | 52 | for (auto u : node->neighbors) { 53 | printHelper(visited, u); 54 | } 55 | } 56 | }; 57 | 58 | int main() { 59 | 60 | UndirectedGraphNode *zero = new UndirectedGraphNode(0); 61 | UndirectedGraphNode *one = new UndirectedGraphNode(1); 62 | UndirectedGraphNode *two = new UndirectedGraphNode(2); 63 | 64 | zero->neighbors = { one, two }; 65 | one->neighbors = { two }; 66 | two->neighbors = { two }; 67 | 68 | Solution s; 69 | printf(" Graph: "); 70 | s.printGraph(zero); 71 | 72 | UndirectedGraphNode *cloned = s.cloneGraph(zero); 73 | 74 | printf("Cloend: "); 75 | s.printGraph(cloned); 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /src/143.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode *Helper(struct ListNode **forward, struct ListNode *node) { 10 | if (node == NULL || node->next == NULL) return node; 11 | 12 | struct ListNode *tail = Helper(forward, node->next); 13 | 14 | if (*forward == tail || (*forward)->next == tail) return tail; 15 | 16 | struct ListNode *t = (*forward)->next; 17 | (*forward)->next = tail; 18 | *forward = t; 19 | tail->next = t; 20 | 21 | return node; 22 | } 23 | 24 | void reorderList(struct ListNode* head) { 25 | if (head == NULL) return; 26 | struct ListNode *p = head; 27 | struct ListNode *mid = Helper(&p, head); 28 | mid->next = NULL; 29 | } 30 | 31 | struct ListNode *createNode(int new_data) { 32 | struct ListNode *new_node = (struct ListNode *)malloc(sizeof(struct ListNode)); 33 | new_node->val = new_data; 34 | new_node->next = NULL; 35 | return new_node; 36 | } 37 | 38 | int main(){ 39 | /* test 1 */ 40 | struct ListNode *l1 = createNode(1); 41 | struct ListNode *p = l1; 42 | int i; 43 | for (i = 2; i <= 5; i++) { 44 | p->next = createNode(i); 45 | p = p->next; 46 | } 47 | p->next = NULL; 48 | 49 | printf("List 1: "); 50 | p = l1; 51 | while (p) { 52 | printf("%d->", p->val); 53 | p = p->next; 54 | } 55 | printf("NIL\n"); 56 | 57 | reorderList(l1); 58 | 59 | printf("Reorder: "); 60 | p = l1; 61 | while (p) { 62 | printf("%d->", p->val); 63 | p = p->next; 64 | } 65 | printf("NIL\n"); 66 | 67 | /* test 2 */ 68 | struct ListNode *l2 = createNode(1); 69 | p = l2; 70 | for (i = 2; i <= 6; i++) { 71 | p->next = createNode(i); 72 | p = p->next; 73 | } 74 | p->next = NULL; 75 | 76 | printf("List 2: "); 77 | p = l2; 78 | while (p) { 79 | printf("%d->", p->val); 80 | p = p->next; 81 | } 82 | printf("NIL\n"); 83 | 84 | reorderList(l2); 85 | 86 | printf("Reorder: "); 87 | p = l2; 88 | while (p) { 89 | printf("%d->", p->val); 90 | p = p->next; 91 | } 92 | printf("NIL\n"); 93 | 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /src/148.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ListNode { 5 | int val; 6 | struct ListNode *next; 7 | }; 8 | 9 | struct ListNode* merge(struct ListNode *left, struct ListNode *right) { 10 | if (left == NULL) return right; 11 | if (right == NULL) return left; 12 | 13 | struct ListNode *ans = NULL; 14 | struct ListNode **p = &ans; 15 | 16 | while (left && right) { 17 | if (left->val <= right->val) { 18 | *p = left; 19 | p = &((*p)->next); 20 | left = left->next; 21 | } 22 | else { 23 | *p = right; 24 | p = &((*p)->next); 25 | right = right->next; 26 | } 27 | } 28 | 29 | if (left) { 30 | *p = left; 31 | } 32 | else if (right) { 33 | *p = right; 34 | } 35 | 36 | return ans; 37 | } 38 | 39 | struct ListNode* sortList(struct ListNode* head) { 40 | if (head == NULL) return NULL; 41 | if (head->next == NULL) return head; 42 | 43 | struct ListNode *p = head; 44 | int len = 0; 45 | while (p) { 46 | len++; 47 | p = p->next; 48 | } 49 | 50 | struct ListNode *mid = head; 51 | struct ListNode *prev = NULL; 52 | int i = len / 2; 53 | while (i--) { 54 | prev = mid; 55 | mid = mid->next; 56 | } 57 | prev->next = NULL; 58 | 59 | struct ListNode *left = sortList(head); 60 | struct ListNode *right = sortList(mid); 61 | 62 | return merge(left, right); 63 | } 64 | 65 | int main() { 66 | struct ListNode *head = (struct ListNode *)calloc(5, sizeof(struct ListNode)); 67 | struct ListNode **p = &head; 68 | int i; 69 | for (i = 0; i < 5; i++) { 70 | (*p)->val = 5 - i; 71 | (*p)->next = *p + 1; 72 | p = &((*p)->next); 73 | } 74 | *p = NULL; 75 | 76 | printf("List: "); 77 | struct ListNode *q = head; 78 | while (q != NULL) { 79 | printf("%d->", q->val); 80 | q = q->next; 81 | } 82 | printf("N\n"); 83 | 84 | struct ListNode *ret = sortList(head); 85 | 86 | printf("Sort result: "); 87 | q = ret; 88 | while (q != NULL) { 89 | printf("%d->", q->val); 90 | q = q->next; 91 | } 92 | printf("N\n"); 93 | 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /src/51.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool isValid(vector &columns, int row) { 11 | for (int i = 0; i < row; i++) { 12 | if (columns[i] == columns[row] 13 | || abs(columns[i] - columns[row]) == (row - i)) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | 20 | void placeQueens(vector > &ret, vector &columns, int row) { 21 | int n = columns.size(); 22 | if (row == n) { /* found one solution! */ 23 | vector solution; 24 | /* build solution vector */ 25 | for (int i = 0; i < n; i++) { 26 | string line(n, '.'); 27 | line[columns[i]] = 'Q'; 28 | solution.push_back(line); 29 | } 30 | ret.push_back(solution); 31 | return; 32 | } 33 | for (int j = 0; j < n; j++) { 34 | /* try to place a queen in this row */ 35 | columns[row] = j; 36 | /* put another queen in next row if this row's position is valid */ 37 | if (isValid(columns, row)) { 38 | placeQueens(ret, columns, row + 1); 39 | } 40 | } 41 | } 42 | 43 | vector > solveNQueens(int n) { 44 | vector > ret; 45 | vector columns(n, 0); 46 | 47 | placeQueens(ret, columns, 0); 48 | 49 | return ret; 50 | } 51 | }; 52 | 53 | int main() { 54 | Solution s; 55 | vector > ret; 56 | ret = s.solveNQueens(4); 57 | 58 | for (int i = 0; i < ret.size(); i++) { 59 | for (int j = 0; j < ret[0].size(); j++) { 60 | cout << ret[i][j] << endl; 61 | } 62 | cout << "----" << endl; 63 | } 64 | 65 | ret = s.solveNQueens(5); 66 | 67 | for (int i = 0; i < ret.size(); i++) { 68 | for (int j = 0; j < ret[0].size(); j++) { 69 | cout << ret[i][j] << endl; 70 | } 71 | cout << "-----" << endl; 72 | } 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /src/54.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Note: The returned array must be malloced, assume caller calls free(). 6 | */ 7 | int *spiralOrder(int **matrix, int matrixRowSize, int matrixColSize) { 8 | int *ret = (int *)malloc(matrixRowSize * matrixColSize * sizeof(int)); 9 | if (matrix == NULL || matrixRowSize == 0 || matrixColSize == 0) 10 | return ret; 11 | 12 | int left = 0; 13 | int right = matrixColSize - 1; 14 | int up = 0; 15 | int down = matrixRowSize - 1; 16 | 17 | int k = 0; 18 | int i; 19 | 20 | while (left <= right && up <= down) { 21 | if (left == right && up == down) { 22 | ret[k++] = matrix[left][up]; 23 | } 24 | else if (left == right) { 25 | for (i = up; i <= down; i++) 26 | ret[k++] = matrix[i][right]; 27 | } 28 | else if (up == down) { 29 | for (i = left; i <= right; i++) 30 | ret[k++] = matrix[up][i]; 31 | } 32 | else { 33 | for (i = left; i <= right - 1; i++) 34 | ret[k++] = matrix[up][i]; 35 | for (i = up; i <= down - 1; i++) 36 | ret[k++] = matrix[i][right]; 37 | for (i = right; i >= left + 1; i--) 38 | ret[k++] = matrix[down][i]; 39 | for (i = down; i >= up + 1; i--) 40 | ret[k++] = matrix[i][left]; 41 | } 42 | left++; 43 | right--; 44 | up++; 45 | down--; 46 | } 47 | 48 | return ret; 49 | } 50 | 51 | int main() { 52 | int rows = 4; 53 | int cols = 3; 54 | int **matrix = (int **)malloc(rows * sizeof(int *)); 55 | int i, j; 56 | for (i = 0; i < rows; i++) { 57 | matrix[i] = (int *)malloc(cols * sizeof(int)); 58 | } 59 | 60 | for (i = 0; i < rows; i++) { 61 | for (j = 0; j < cols; j++) { 62 | matrix[i][j] = i * cols + j + 1; 63 | printf("%d ", matrix[i][j]); 64 | } 65 | printf("\n"); 66 | } 67 | printf("------\n"); 68 | 69 | int *ret = spiralOrder(matrix, rows, cols); 70 | 71 | int size = rows * cols; 72 | for (i = 0; i < size; i++) { 73 | printf("%d ", ret[i]); 74 | } 75 | printf("\n"); 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /src/219.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct HashNode { 6 | int data; 7 | int index; 8 | struct HashNode *next; 9 | }; 10 | 11 | static inline int hash(int num, int size) { 12 | int index = num % size; 13 | return (index > 0) ? (index) : (-index); 14 | } 15 | 16 | bool containsNearbyDuplicate(int* nums, int numsSize, int k) { 17 | if (numsSize < 2) return false; 18 | bool duplicated = false; 19 | 20 | int hash_size = numsSize / 2 + 1; /* proper size can be faster */ 21 | struct HashNode **hash_table 22 | = (struct HashNode **)calloc(hash_size, sizeof(struct HashNode *)); 23 | 24 | int i; 25 | for (i = 0; i < numsSize; i++) { 26 | int index = hash(nums[i], hash_size); 27 | struct HashNode **p = hash_table + index; 28 | 29 | while (*p) { 30 | if ((*p)->data == nums[i]) { 31 | int distance = abs((*p)->index - i); 32 | if (distance <= k) { 33 | duplicated = true; 34 | goto OUT; 35 | } 36 | else { 37 | (*p)->index = i; /* update to nearer index */ 38 | } 39 | } 40 | p = &((*p)->next); 41 | } 42 | 43 | struct HashNode *new_node 44 | = (struct HashNode *)malloc(sizeof(struct HashNode)); 45 | new_node->data = nums[i]; 46 | new_node->index = i; 47 | new_node->next = NULL; 48 | 49 | *p = new_node; 50 | } 51 | 52 | OUT: 53 | for (i = 0; i < hash_size; i++) { 54 | struct HashNode *t = hash_table[i]; 55 | struct HashNode *x = NULL; 56 | while (t) { 57 | x = t->next; 58 | free(t); 59 | t = x; 60 | } 61 | } 62 | free(hash_table); 63 | 64 | return duplicated; 65 | } 66 | 67 | int main() { 68 | int nums[] = { 1, 3, 5, 7, 9, 2, 7, 4, 7 }; 69 | /* should be true */ 70 | printf("%d\n", containsNearbyDuplicate(nums, sizeof(nums) / sizeof(nums[0]), 2)); 71 | 72 | /* should be false */ 73 | printf("%d\n", containsNearbyDuplicate(nums, sizeof(nums) / sizeof(nums[0]), 1)); 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /src/147.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct ListNode { 6 | int val; 7 | struct ListNode *next; 8 | }; 9 | 10 | struct ListNode* insertionSortList(struct ListNode* head) { 11 | if (head == NULL) return NULL; 12 | 13 | struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode)); 14 | dummy->val = 0; 15 | dummy->next = NULL; 16 | struct ListNode *t = dummy; 17 | 18 | struct ListNode *p; 19 | struct ListNode *min_ptr, *min_prev; /* prev node of min node */ 20 | int min_val; 21 | p = head; 22 | 23 | while (p) { 24 | min_val = p->val; 25 | min_ptr = p; 26 | min_prev = NULL; 27 | 28 | struct ListNode *q = p->next; 29 | struct ListNode *prev = p; 30 | while (q) { 31 | if (q->val < min_val) { 32 | min_val = q->val; 33 | min_prev = prev; 34 | min_ptr = q; 35 | } 36 | prev = q; 37 | q = q->next; 38 | } 39 | 40 | if (p == min_ptr) { /* if min node is p, we don't need to modify list */ 41 | p = p->next; /* just move forward p, and the min_prev is still */ 42 | } /* NULL now. */ 43 | else { 44 | min_prev->next = min_ptr->next; /* take node from list */ 45 | } 46 | t->next = min_ptr; 47 | t = t->next; 48 | } 49 | t->next = NULL; 50 | 51 | t = dummy->next; 52 | free(dummy); 53 | 54 | return t; 55 | } 56 | 57 | void print(struct ListNode* head) { 58 | while (head) { 59 | printf("%d ", head->val); 60 | head = head->next; 61 | } 62 | printf("NIL\n"); 63 | } 64 | 65 | int main() { 66 | int n = 10; 67 | struct ListNode *head = (struct ListNode *)calloc(n, sizeof(struct ListNode)); 68 | struct ListNode **p = &head; 69 | int i; 70 | 71 | srand(time(NULL)); 72 | for (i = 0; i < n; i++) { 73 | (*p)->val = rand() % n; 74 | (*p)->next = *p + 1; 75 | p = &((*p)->next); 76 | } 77 | *p = NULL; 78 | 79 | printf("List: "); 80 | print(head); 81 | 82 | struct ListNode *new_head = insertionSortList(head); 83 | 84 | printf("Sorted: "); 85 | print(new_head); 86 | 87 | return 0; 88 | } 89 | --------------------------------------------------------------------------------