set = new HashSet<>();
4 | for(int i=0; i < nums.length; i++) {
5 | set.add(nums[i]);
6 | }
7 | return nums.length != set.size();
8 | }
9 | }
--------------------------------------------------------------------------------
/217/ Contains Duplicate/Solution.kt:
--------------------------------------------------------------------------------
1 | package `217`.` Contains Duplicate`
2 |
3 | class Solution {
4 | fun containsDuplicate(nums: IntArray): Boolean {
5 | return nums.toHashSet().size < nums.size
6 | }
7 | }
--------------------------------------------------------------------------------
/231/ Power of Two/Solution.kt:
--------------------------------------------------------------------------------
1 | package `231`.` Power of Two`
2 |
3 | class Solution {
4 | fun isPowerOfTwo(n: Int): Boolean {
5 | return n > 0 && (n and n - 1 == 0)
6 | }
7 | }
--------------------------------------------------------------------------------
/24-swap-nodes-in-pairs/24-swap-nodes-in-pairs.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * struct ListNode {
4 | * int val;
5 | * ListNode *next;
6 | * ListNode() : val(0), next(nullptr) {}
7 | * ListNode(int x) : val(x), next(nullptr) {}
8 | * ListNode(int x, ListNode *next) : val(x), next(next) {}
9 | * };
10 | */
11 | class Solution {
12 | public:
13 | ListNode* swapPairs(ListNode* head) {
14 | if(!head || !head->next)
15 | return head;
16 |
17 | ListNode* next = head->next;
18 | head->next = swapPairs(head->next->next);
19 | next->next = head;
20 |
21 | return next;
22 | }
23 | };
--------------------------------------------------------------------------------
/24-swap-nodes-in-pairs/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/26-remove-duplicates-from-sorted-array/26-remove-duplicates-from-sorted-array.kt:
--------------------------------------------------------------------------------
1 | class Solution {
2 | fun removeDuplicates(nums: IntArray): Int {
3 | var cnt = if (nums.size > 0) 1 else 0
4 |
5 | for (i in 1 until nums.size) {
6 | if(nums[i] == nums[i-1]) continue
7 | nums[cnt] = nums[i]
8 | cnt++
9 | }
10 | return cnt
11 | }
12 | }
--------------------------------------------------------------------------------
/26-remove-duplicates-from-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/26-remove-duplicates-from-sorted-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
2 |
3 |
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums
. More formally, if there are k
elements after removing the duplicates, then the first k
elements of nums
should hold the final result. It does not matter what you leave beyond the first k
elements.
4 |
5 |
Return k
after placing the final result in the first k
slots of nums
.
6 |
7 |
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
8 |
9 |
Custom Judge:
10 |
11 |
The judge will test your solution with the following code:
12 |
13 |
int[] nums = [...]; // Input array
14 | int[] expectedNums = [...]; // The expected answer with correct length
15 |
16 | int k = removeDuplicates(nums); // Calls your implementation
17 |
18 | assert k == expectedNums.length;
19 | for (int i = 0; i < k; i++) {
20 | assert nums[i] == expectedNums[i];
21 | }
22 |
23 |
24 |
If all assertions pass, then your solution will be accepted.
25 |
26 |
27 |
Example 1:
28 |
29 |
Input: nums = [1,1,2]
30 | Output: 2, nums = [1,2,_]
31 | Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
32 | It does not matter what you leave beyond the returned k (hence they are underscores).
33 |
34 |
35 |
Example 2:
36 |
37 |
Input: nums = [0,0,1,1,1,2,2,3,3,4]
38 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
39 | Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
40 | It does not matter what you leave beyond the returned k (hence they are underscores).
41 |
42 |
43 |
44 |
Constraints:
45 |
46 |
47 | 1 <= nums.length <= 3 * 104
48 | -100 <= nums[i] <= 100
49 | nums
is sorted in non-decreasing order.
50 |
51 |
--------------------------------------------------------------------------------
/27-remove-element/27-remove-element.kt:
--------------------------------------------------------------------------------
1 | class Solution {
2 | fun removeElement(nums: IntArray, `val`: Int): Int {
3 | var res =0
4 | for (i in 0 until nums.size) {
5 | if(nums[i] != `val`) {
6 | nums[res++] = nums[i]
7 | }
8 | }
9 | return res
10 | }
11 | }
--------------------------------------------------------------------------------
/27-remove-element/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/27-remove-element/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The relative order of the elements may be changed.
2 |
3 |
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums
. More formally, if there are k
elements after removing the duplicates, then the first k
elements of nums
should hold the final result. It does not matter what you leave beyond the first k
elements.
4 |
5 |
Return k
after placing the final result in the first k
slots of nums
.
6 |
7 |
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
8 |
9 |
Custom Judge:
10 |
11 |
The judge will test your solution with the following code:
12 |
13 |
int[] nums = [...]; // Input array
14 | int val = ...; // Value to remove
15 | int[] expectedNums = [...]; // The expected answer with correct length.
16 | // It is sorted with no values equaling val.
17 |
18 | int k = removeElement(nums, val); // Calls your implementation
19 |
20 | assert k == expectedNums.length;
21 | sort(nums, 0, k); // Sort the first k elements of nums
22 | for (int i = 0; i < actualLength; i++) {
23 | assert nums[i] == expectedNums[i];
24 | }
25 |
26 |
27 |
If all assertions pass, then your solution will be accepted.
28 |
29 |
30 |
Example 1:
31 |
32 |
Input: nums = [3,2,2,3], val = 3
33 | Output: 2, nums = [2,2,_,_]
34 | Explanation: Your function should return k = 2, with the first two elements of nums being 2.
35 | It does not matter what you leave beyond the returned k (hence they are underscores).
36 |
37 |
38 |
Example 2:
39 |
40 |
Input: nums = [0,1,2,2,3,0,4,2], val = 2
41 | Output: 5, nums = [0,1,4,0,3,_,_,_]
42 | Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
43 | Note that the five elements can be returned in any order.
44 | It does not matter what you leave beyond the returned k (hence they are underscores).
45 |
46 |
47 |
48 |
Constraints:
49 |
50 |
51 | 0 <= nums.length <= 100
52 | 0 <= nums[i] <= 50
53 | 0 <= val <= 100
54 |
55 |
--------------------------------------------------------------------------------
/278/ First Bad Version/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int firstBadVersion(int n) {
4 | int l = 1, r = n;
5 | while (l < r) {
6 | int mid = l + (r - l) / 2;
7 | if (isBadVersion(mid)) {
8 | r = mid;
9 | } else {
10 | l = mid + 1;
11 | }
12 | }
13 | return r;
14 | }
15 | };
16 |
17 |
--------------------------------------------------------------------------------
/278/ First Bad Version/solution.kt:
--------------------------------------------------------------------------------
1 | package `278`.` First Bad Version`
2 |
3 | class Solution: VersionControl() {
4 | override fun firstBadVersion(n: Int) : Int {
5 | if (n == 1) {
6 | return 1
7 | }
8 | var begin = 1
9 | var end = n
10 | while (begin < end) {
11 | val mid = begin + (end - begin) / 2
12 | if (isBadVersion(mid)) {
13 | end = mid
14 | } else if (!isBadVersion(mid) && isBadVersion(mid + 1)) {
15 | return mid + 1
16 | } else
17 | begin = mid + 1
18 | }
19 |
20 | if (begin!=n && isBadVersion(begin)) {
21 | return begin
22 | }
23 | return -1
24 |
25 | }
26 | }
--------------------------------------------------------------------------------
/28-implement-strstr/28-implement-strstr.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int strStr(String haystack, String needle) {
3 | if (needle == null || needle.length() == 0) {
4 | return 0;
5 | }
6 |
7 | if(haystack == null || haystack.length() == 0) {
8 | return -1;
9 | }
10 |
11 | for(int i = 0; i < haystack.length() - needle.length() + 1; i++ ) {
12 | int j;
13 | for(j=0; j < needle.length(); j++) {
14 | if (haystack.charAt(i+ j) != needle.charAt(j)) {
15 | break;
16 | }
17 | }
18 | if(j == needle.length()) {
19 | return i;
20 | }
21 | }
22 | return -1;
23 | }
24 | }
--------------------------------------------------------------------------------
/28-implement-strstr/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/28-implement-strstr/README.md:
--------------------------------------------------------------------------------
1 | Easy
Implement strStr().
2 |
3 |
Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle
is not part of haystack
.
4 |
5 |
Clarification:
6 |
7 |
What should we return when needle
is an empty string? This is a great question to ask during an interview.
8 |
9 |
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
10 |
11 |
12 |
Example 1:
13 |
14 |
Input: haystack = "hello", needle = "ll"
15 | Output: 2
16 |
17 |
18 |
Example 2:
19 |
20 |
Input: haystack = "aaaaa", needle = "bba"
21 | Output: -1
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | 1 <= haystack.length, needle.length <= 104
29 | haystack
and needle
consist of only lowercase English characters.
30 |
31 |
--------------------------------------------------------------------------------
/283/ Move Zeroes/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public void moveZeroes(int[] nums) {
3 | int k = 0;
4 | for (int i = 0; i < nums.length; i++) {
5 | if (nums[i] != 0) {
6 | if (k != 0) {
7 | nums[i - k] = nums[i];
8 | nums[i] = 0;
9 | }
10 | } else {
11 | k++;
12 | }
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/283/ Move Zeroes/Solution.kt:
--------------------------------------------------------------------------------
1 | package `283`.` Move Zeroes`
2 |
3 | class Solution {
4 | fun moveZeroes(nums: IntArray): Unit {
5 | var zeroes = 0
6 | nums.indices.forEach {
7 | when (nums[it]) {
8 | 0 -> zeroes++
9 | else -> {
10 | if (zeroes != 0) {
11 | nums[it - zeroes] = nums[it]
12 | nums[it] = 0
13 | }
14 | }
15 | }
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/29-divide-two-integers/29-divide-two-integers.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int divide(int dividend, int divisor) {
3 | //check if negative answer
4 | boolean isNeg = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
5 |
6 | //use long to take care of overflow
7 | long ldividend = Math.abs((long)dividend);
8 | long ldivisor = Math.abs((long)divisor);
9 |
10 | long res = 0, curr = 1;
11 | long sub = ldivisor;
12 |
13 | while (ldividend >= ldivisor) {
14 | if (ldividend >= sub) {
15 | res += curr;
16 | ldividend -= sub;
17 | sub = sub << 1; //sub = sub * 2
18 | curr = curr << 1; //curr = curr * 2
19 | }
20 | else {
21 | sub = sub >> 1;
22 | curr = curr >> 1;
23 | }
24 | }
25 |
26 | res = isNeg ? -res : res;
27 |
28 | return (int) (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? Integer.MAX_VALUE : res);
29 | }
30 | }
--------------------------------------------------------------------------------
/29-divide-two-integers/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/3/ Longest Substring Without Repeating Characters/Solution.kt:
--------------------------------------------------------------------------------
1 | package `3`.` Longest Substring Without Repeating Characters`
2 |
3 | /////old version .toInt()
4 | class Solution {
5 | fun lengthOfLongestSubstring(s: String): Int {
6 | val freq = IntArray(256) { 0 }
7 | var l = 0
8 | var r = -1
9 | var res = 0
10 | while (l < s.length) {
11 | if (r + 1 < s.length && freq[s[r + 1].toInt()] == 0) freq[s[++r].toInt()]++
12 | else freq[s[l++].toInt()]--
13 |
14 | res = maxOf(res, r - l + 1)
15 | }
16 | return res
17 | }
18 | }
19 |
20 |
21 | ////////////// For Kotlin 1.5 new version
22 | //class Solution {
23 | // fun lengthOfLongestSubstring(s: String): Int {
24 | // val freq = IntArray(256) { 0 }
25 | // var l = 0
26 | // var r = -1
27 | // var res = 0
28 | // while (l < s.length) {
29 | // if (r + 1 < s.length && freq[s[r + 1].code] == 0) freq[s[++r].code]++
30 | // else freq[s[l++].code]--
31 | //
32 | // res = maxOf(res, r - l + 1)
33 | // }
34 | // return res
35 | // }
36 | //}
37 |
--------------------------------------------------------------------------------
/33/ Search in Rotated Sorted Array/Solution.kt:
--------------------------------------------------------------------------------
1 | package `33`.` Search in Rotated Sorted Array`
2 |
3 | class Solution {
4 | fun search(nums: IntArray, target: Int): Int {
5 | if (nums.isEmpty()) {
6 | return -1
7 | }
8 | var left = 0
9 | var right = nums.size - 1
10 | while (left + 1 < right) {
11 | val mid = left + (right - left) / 2
12 | when {
13 | nums[mid] == target -> return mid
14 | nums[mid] >= nums[0] -> {
15 | if (nums[left] <= target && target <= nums[mid]) {
16 | right = mid
17 | } else {
18 | left = mid
19 | }
20 | }
21 |
22 | nums[mid] <= nums[nums.size - 1] -> {
23 | if (nums[mid] <= target && target <= nums[right]) {
24 | left = mid
25 | } else {
26 | right = mid
27 | }
28 | }
29 | }
30 | }
31 | return when (target) {
32 | nums[left] -> left
33 | nums[right] -> right
34 | else -> -1
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/34/ Find First and Last Position of Element in Sorted Array/Solution.kt:
--------------------------------------------------------------------------------
1 | package `34`.` Find First and Last Position of Element in Sorted Array`
2 |
3 | class Solution {
4 | fun searchRange(nums: IntArray, target: Int): IntArray {
5 |
6 | if (nums.size == 0) return intArrayOf(-1, -1)
7 |
8 | var l: Int = 0
9 | var r: Int = nums.size - 1
10 | var mid = 0
11 | var res = IntArray(2)
12 |
13 | while (l < r) {
14 | mid = (l + r) / 2
15 | if (nums[mid] < target) {
16 | l = mid + 1
17 | } else {
18 | r = mid
19 | }
20 | }
21 |
22 | if (nums[l] != target) return intArrayOf(-1, -1)
23 | res[0] = l
24 |
25 | r = nums.size - 1
26 |
27 | while (l < r) {
28 | mid = (l + r) / 2 + 1
29 | if (nums[mid] == target) {
30 | l = mid
31 | } else {
32 | r = mid - 1
33 | }
34 | }
35 | res[1] = l
36 | return res
37 | }
38 | }
--------------------------------------------------------------------------------
/344/ Reverse String/Solution.kt:
--------------------------------------------------------------------------------
1 | package `344`.` Reverse String`
2 |
3 | class Solution {
4 | private fun swap(s: CharArray, left: Int, right: Int) {
5 | var temp = s[left]
6 | s[left] = s[right]
7 | s[right] = temp
8 | }
9 |
10 | fun reverseString(s: CharArray): Unit {
11 | var left = 0
12 | var right = s.size - 1
13 |
14 | while (left < right) {
15 | swap(s, left, right)
16 |
17 | left++
18 | right--
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/35/ Search Insert Position/Solution.kt:
--------------------------------------------------------------------------------
1 | package `35`.` Search Insert Position`
2 |
3 | class Solution {
4 | fun searchInsert(nums: IntArray, target: Int): Int {
5 | var low = 0
6 | var high = nums.size - 1
7 | while (low <= high) {
8 | val mid = (low + high) ushr 1
9 | when {
10 | target < nums[mid] -> high = mid - 1
11 | target > nums[mid] -> low = mid + 1
12 | else -> return mid
13 | }
14 | }
15 | return low
16 | }
17 | }
--------------------------------------------------------------------------------
/350-Intersection of Two Arrays II/350-Intersection of Two Arrays II.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public int[] intersect(int[] nums1, int[] nums2) {
3 | HashMap map = new HashMap<>();
4 | ArrayList arr = new ArrayList<>();
5 | for (int num : nums1) {
6 | if (map.containsKey(num)) {
7 | map.put(num, map.get(num) + 1);
8 | } else {
9 | map.put(num, 1);
10 | }
11 | }
12 | for (int num : nums2) {
13 | if (map.containsKey(num) && map.get(num) > 0) {
14 | arr.add(num);
15 | map.put(num, map.get(num) - 1);
16 | }
17 | }
18 | int[] res = new int[arr.size()];
19 | int k = 0;
20 | for (Integer num : arr) {
21 | res[k++] = num;
22 | }
23 | return res;
24 | }
25 | }
--------------------------------------------------------------------------------
/350/Solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector intersect(vector &nums1, vector &nums2) {
4 | sort(nums1.begin(), nums1.end());
5 | sort(nums2.begin(), nums2.end());
6 | vector solution;
7 | int index = 0;
8 | bool finished = false;
9 | for (int i = 0; i < nums1.size() && !finished; i++) {
10 | while (index < nums2.size() && nums1[i] > nums2[index]) {
11 | index++;
12 | }
13 | if (index == nums2.size()) {
14 | finished = true;
15 | } else if (nums1[i] == nums2[index]) {
16 | solution.push_back(nums1[i]);
17 | index++;
18 | }
19 | }
20 | return solution;
21 | }
22 | };
--------------------------------------------------------------------------------
/438/ Find All Anagrams in a String/Solution.kt:
--------------------------------------------------------------------------------
1 | package `438`.` Find All Anagrams in a String`
2 |
3 | class Solution {
4 | fun findAnagrams(s: String, p: String): List {
5 | if (s.isEmpty() || s.length < p.length) {
6 | return emptyList()
7 | }
8 |
9 | val result = mutableListOf()
10 | val hashArray = IntArray(26)
11 | for (index in p.indices) {
12 | ++hashArray[p[index] - 'a']
13 | }
14 |
15 | var left = 0
16 | var count = 0
17 |
18 | for (index in s.indices) {
19 | if (--hashArray[s[index] - 'a'] >= 0) {
20 | ++count
21 | }
22 | if (index >= p.length) {
23 | if (hashArray[s[left++] - 'a']++ >= 0) {
24 | --count
25 | }
26 | }
27 | if (count == p.length) {
28 | result.add(left)
29 | }
30 | }
31 | return result
32 | }
33 | }
--------------------------------------------------------------------------------
/46/ Permutations/Solution.kt:
--------------------------------------------------------------------------------
1 | package `46`.` Permutations`
2 |
3 | class Solution {
4 | private val res = ArrayList>()
5 | fun permute(nums: IntArray): List> {
6 | permutation(nums, 0, nums.size - 1)
7 | return res
8 | }
9 |
10 | private fun permutation(list: IntArray, start: Int, length: Int) {
11 | if (start == length) res.add(list.toMutableList())
12 | else (start..length).forEach { i ->
13 | swap(list, start, i)
14 | permutation(list, start + 1, length)
15 | swap(list, start, i)
16 | }
17 | }
18 |
19 | private fun swap(nums: IntArray, i: Int, j: Int) {
20 | val temp = nums[i]
21 | nums[i] = nums[j]
22 | nums[j] = temp
23 | }
24 | }
--------------------------------------------------------------------------------
/462-minimum-moves-to-equal-array-elements-ii/462-minimum-moves-to-equal-array-elements-ii.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int minMoves2(int[] nums) {
3 | int res = 0;
4 | if (nums == null || nums.length <= 1) return res;
5 | int start = 0;
6 | int end = nums.length -1 ;
7 | Arrays.sort(nums);
8 | while(start < end) {
9 | res += nums[end] - nums[start];
10 | start++;
11 | end--;
12 | }
13 | return res;
14 | }
15 | }
--------------------------------------------------------------------------------
/462-minimum-moves-to-equal-array-elements-ii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/53-Maximum-Subarray/53-Maximum-Subarray.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int maxSubArray(int[] nums) {
3 | int total = 0, max = Integer.MIN_VALUE;
4 | for (int i = 0; i < nums.length; i++) {
5 | total += nums[i];
6 | if (max < total)
7 | max = total;
8 | if (total <= 0)
9 | total = 0;
10 | }
11 | return max;
12 | }
13 | }
--------------------------------------------------------------------------------
/53/ Maximum Subarray/Solution.kt:
--------------------------------------------------------------------------------
1 | package `53`.` Maximum Subarray`
2 |
3 | class Solution {
4 | fun maxSubArray(nums: IntArray): Int {
5 | var sum = 0
6 | var maxa = -2147483647
7 |
8 | nums.forEach { a ->
9 | if (sum < 0) {
10 | sum = a
11 | } else {
12 | sum += a
13 | }
14 | maxa = Math.max(sum, maxa)
15 | }
16 | return maxa
17 | }
18 | }
--------------------------------------------------------------------------------
/542/ 01 Matrix/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public final int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
3 |
4 | public int[][] updateMatrix(int[][] mat) {
5 | int rowCount = mat.length;
6 | int colCount = mat[0].length;
7 | int[][] res = new int[rowCount][colCount];
8 |
9 | //Initialize
10 | for (int i = 0; i < rowCount; ++i) {
11 | for (int j = 0; j < colCount; ++j) {
12 | res[i][j] = Integer.MAX_VALUE;
13 | }
14 | }
15 |
16 |
17 | // Update from top-left
18 | for (int i = 0; i < rowCount; ++i) {
19 | for (int j = 0; j < colCount; ++j) {
20 | update(mat, res, rowCount, colCount, i, j);
21 | }
22 | }
23 |
24 |
25 | // Update from bottom-right
26 | for (int i = rowCount - 1; i > -1; --i) {
27 | for (int j = colCount - 1; j > -1; --j) {
28 | update(mat, res, rowCount, colCount, i, j);
29 | }
30 | }
31 |
32 |
33 | return res;
34 |
35 | }
36 |
37 | public void update(int[][] src, int[][] out, int rowCount, int colCount, int i, int j) {
38 | if (src[i][j] == 0) {
39 | out[i][j] = 0;
40 | return;
41 | }
42 |
43 | for (int[] d : directions) {
44 | int x = i + d[0];
45 | int y = j + d[1];
46 | if (0 <= x && x < rowCount && 0 <= y && y < colCount && out[x][y] != Integer.MAX_VALUE && out[x][y] + 1 < out[i][j]) {
47 | out[i][j] = out[x][y] + 1;
48 | }
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/547/ Number of Provinces/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 | public int findCircleNum(int[][] isConnected) {
5 | int n = isConnected.length;
6 | boolean[] visited = new boolean[n];
7 | int components = 0;
8 | for (int vertex = 0; vertex < n; vertex++) {
9 | if (!visited[vertex]) {
10 | visited[vertex] = true;
11 | components++;
12 | visitNeighbors(vertex, isConnected, visited);
13 | }
14 | }
15 | return components;
16 | }
17 |
18 | private void visitNeighbors(int vertex, int[][] isConnected, boolean[] visited) {
19 | for (int v = 0; v < isConnected.length; v++) {
20 | if (isConnected[vertex][v] == 1 && !visited[v]) {
21 | visited[v] = true;
22 | visitNeighbors(v, isConnected, visited);
23 | }
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/557/ Reverse Words in a String III/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public String reverseWords(String s) {
3 | if (s == null || s.length() <= 1) {
4 | return s;
5 | }
6 |
7 | char[] str = s.toCharArray();
8 | int start = 0;
9 | for (int i = 0; i < str.length; i++) {
10 | if (str[i] == ' ') {
11 | reverse(str, start, i - 1);
12 | start = i + 1;
13 | } else if (i == str.length - 1) {
14 | reverse(str, start, i);
15 | }
16 | }//end for
17 | return String.valueOf(str);
18 | }
19 |
20 | public void reverse(char[] s, int start, int end) {
21 | while (start < end) {
22 | char temp = s[start];
23 | s[start] = s[end];
24 | s[end] = temp;
25 | start++;
26 | end--;
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/566-Reshape the Matrix/566-Reshape the Matrix.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int[][] matrixReshape(int[][] mat, int r, int c) {
3 | int numberOfElement = mat.length * mat[0].length;
4 | if (numberOfElement != r * c)
5 | return mat;
6 |
7 | int[] expandedArrary = new int[numberOfElement];
8 | int k = 0;
9 | for (int i = 0; i < mat.length; i++) {
10 | for (int j = 0; j < mat[i].length; j++) {
11 | expandedArrary[k] = mat[i][j];
12 | k++;
13 | }
14 | }
15 |
16 | int[][] answer = new int[r][c];
17 | int i = 0;
18 | int j = 0;
19 | for (k = 0; k < numberOfElement; k++) {
20 | answer[i][j] = expandedArrary[k];
21 | j++;
22 | if (j == c){
23 | j = 0;
24 | i++;
25 | }
26 |
27 | }
28 | return answer;
29 | }
30 | }
--------------------------------------------------------------------------------
/567/ Permutation in String/Solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool checkInclusion(string s1, string s2) {
4 | int m = s1.size(), n = s2.size();
5 | if (m > n) return false;
6 |
7 | vector cnt1(26);
8 | vector cnt2(26);
9 | for (int i = 0; i < m; ++i) {
10 | cnt1[s1[i] - 'a']++;
11 | cnt2[s2[i] - 'a']++;
12 | }
13 |
14 | if (cnt1 == cnt2) return true;
15 |
16 | for (int i = m; i < n; ++i) {
17 | cnt2[s2[i - m] - 'a']--;
18 | cnt2[s2[i] - 'a']++;
19 | if (cnt1 == cnt2) {
20 | return true;
21 | }
22 | }
23 | return false;
24 | }
25 | };
--------------------------------------------------------------------------------
/567/ Permutation in String/Solution.kt:
--------------------------------------------------------------------------------
1 | package `567`.` Permutation in String`
2 |
3 | class Solution {
4 | fun checkInclusion(s1: String, s2: String): Boolean {
5 | if (s1.length > s2.length) return false
6 | val slide = IntArray(26) { 0 }
7 | s1.indices.forEach { slide[s1[it] - 'a']++ }
8 | (0 until s2.length).forEach {
9 | slide[s2[it] - 'a']--
10 | if (it >= s1.length) slide[s2[it - s1.length] - 'a']++
11 | if (slide.none { it != 0 }) return true
12 | }
13 | return false
14 | }
15 | }
--------------------------------------------------------------------------------
/572/ Subtree of Another Tree/Solution.kt:
--------------------------------------------------------------------------------
1 | package `572`.` Subtree of Another Tree`
2 |
3 |
4 | var ti = TreeNode(5)
5 | var v = ti.`val`
6 |
7 | class TreeNode(var `val`: Int) {
8 | var left: TreeNode? = null
9 | var right: TreeNode? = null
10 | }
11 |
12 | class Solution {
13 | fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean {
14 | if (null == root || null == subRoot) return root == subRoot
15 | return isSame(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
16 | }
17 |
18 | private fun isSame(node: TreeNode?, t: TreeNode?): Boolean {
19 | if (node == null || t == null) return node == t
20 | return node.`val` == t.`val` && isSame(node.left, t.left) && isSame(node.right, t.right)
21 | }
22 | }
--------------------------------------------------------------------------------
/58-length-of-last-word/58-length-of-last-word.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int lengthOfLastWord(String s) {
3 | if (s == null || s.length() == 0) {
4 | return 0;
5 | }
6 | s = s.trim();
7 | for(int i = s.length() - 1; i >= 0; i--) {
8 | if(s.charAt(i) == ' ') {
9 | return s.length() - i - 1;
10 | }
11 | }
12 |
13 | return s.length();
14 | }
15 | }
--------------------------------------------------------------------------------
/58-length-of-last-word/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/58-length-of-last-word/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a string s
consisting of words and spaces, return the length of the last word in the string.
2 |
3 |
A word is a maximal substring consisting of non-space characters only.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: s = "Hello World"
9 | Output: 5
10 | Explanation: The last word is "World" with length 5.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: s = " fly me to the moon "
16 | Output: 4
17 | Explanation: The last word is "moon" with length 4.
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: s = "luffy is still joyboy"
23 | Output: 6
24 | Explanation: The last word is "joyboy" with length 6.
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= s.length <= 104
32 | s
consists of only English letters and spaces ' '
.
33 | - There will be at least one word in
s
.
34 |
35 |
--------------------------------------------------------------------------------
/617/ Merge Two Binary Trees/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
3 | TreeNode node;
4 | if (t1 == null && t2 == null) {
5 | node = null;
6 | } else if (t1 == null) {
7 | node = new TreeNode(t2.val);
8 | node.left = mergeTrees(null, t2.left);
9 | node.right = mergeTrees(null, t2.right);
10 | } else if (t2 == null) {
11 | node = new TreeNode(t1.val);
12 | node.left = mergeTrees(t1.left, null);
13 | node.right = mergeTrees(t1.right, null);
14 | } else {
15 | node = new TreeNode(t1.val + t2.val);
16 | node.left = mergeTrees(t1.left, t2.left);
17 | node.right = mergeTrees(t1.right, t2.right);
18 | }
19 | return node;
20 | }
21 | }
--------------------------------------------------------------------------------
/66-plus-one/66-plus-one.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector plusOne(vector& digits) {
4 | int n = digits.size();
5 | int pos = n -1;
6 | while(pos >= 0 && digits[pos] == 9) {
7 | digits[pos] = 0;
8 | pos--;
9 | }
10 |
11 | if(pos < 0) {
12 | digits.insert(digits.begin(), 1);
13 | }else {
14 | digits[pos]++;
15 | }
16 |
17 | return digits;
18 | }
19 | };
--------------------------------------------------------------------------------
/66-plus-one/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/66-plus-one/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
's.
2 |
3 |
Increment the large integer by one and return the resulting array of digits.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: digits = [1,2,3]
9 | Output: [1,2,4]
10 | Explanation: The array represents the integer 123.
11 | Incrementing by one gives 123 + 1 = 124.
12 | Thus, the result should be [1,2,4].
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: digits = [4,3,2,1]
18 | Output: [4,3,2,2]
19 | Explanation: The array represents the integer 4321.
20 | Incrementing by one gives 4321 + 1 = 4322.
21 | Thus, the result should be [4,3,2,2].
22 |
23 |
24 |
Example 3:
25 |
26 |
Input: digits = [9]
27 | Output: [1,0]
28 | Explanation: The array represents the integer 9.
29 | Incrementing by one gives 9 + 1 = 10.
30 | Thus, the result should be [1,0].
31 |
32 |
33 |
34 |
Constraints:
35 |
36 |
37 | 1 <= digits.length <= 100
38 | 0 <= digits[i] <= 9
39 | digits
does not contain any leading 0
's.
40 |
41 |
--------------------------------------------------------------------------------
/67-add-binary/67-add-binary.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string addBinary(string a, string b) {
4 | int N = max(a.size(), b.size()) + 1;
5 |
6 | //padding
7 | a.insert(a.begin(), N-a.size(), '0');
8 | b.insert(b.begin(), N-b.size(), '0');
9 |
10 | reverse(a.begin(), a.end());
11 | reverse(b.begin(), b.end());
12 |
13 | int i = 0, carry = 0;
14 | //add b to a
15 | for(int i = 0; i < N; i++) {
16 | int ai = a[i] - '0', bi = b[i] - '0';
17 | int sumi = ai + bi + carry;
18 | switch(sumi) {
19 | case 3:
20 | a[i] = '1';
21 | carry = 1;
22 | break;
23 | case 2:
24 | a[i] = '0';
25 | carry = 1;
26 | break;
27 | case 1:
28 | a[i] = '1';
29 | carry = 0 ;
30 | break;
31 | }
32 | }
33 |
34 | if(a[N-1] == '0') a.resize(N-1);
35 | reverse(a.begin(), a.end());
36 | return a;
37 | }
38 | };
--------------------------------------------------------------------------------
/67-add-binary/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/67-add-binary/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two binary strings a
and b
, return their sum as a binary string.
2 |
3 |
4 |
Example 1:
5 |
Input: a = "11", b = "1"
6 | Output: "100"
7 |
Example 2:
8 |
Input: a = "1010", b = "1011"
9 | Output: "10101"
10 |
11 |
12 |
Constraints:
13 |
14 |
15 | 1 <= a.length, b.length <= 104
16 | a
and b
consist only of '0'
or '1'
characters.
17 | - Each string does not contain leading zeros except for the zero itself.
18 |
19 |
--------------------------------------------------------------------------------
/695. Max Area of Island/Solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxAreaOfIsland(vector > &grid) {
4 | int m = grid.size();
5 | int n = grid[0].size();
6 | int res = 0;
7 | for (int i = 0; i < m; i++)
8 | for (int j = 0; j < n; j++)
9 | if (grid[i][j] == 1)
10 | res = max(res, dfs(grid, i, j));
11 | return res;
12 | }
13 |
14 | int dfs(vector > &grid, int i, int j) {
15 | int m = grid.size();
16 | int n = grid[0].size();
17 |
18 | if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0)
19 | return 0;
20 | grid[i][j] = 0;
21 |
22 | return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + dfs(grid, i, j + 1) + dfs(grid, i, j - 1) + 1;
23 | }
24 | };
--------------------------------------------------------------------------------
/7-reverse-integer/7-reverse-integer.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int reverse(int x) {
3 | int res = 0;
4 |
5 | while (x != 0) {
6 | int tail = x % 10;
7 | int newRes = res * 10 + tail;
8 | if ((newRes - tail) / 10 != res) {
9 | return 0;
10 | }
11 | res = newRes;
12 | x = x / 10;
13 | }
14 | return res;
15 | }
16 | }
--------------------------------------------------------------------------------
/7-reverse-integer/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/7-reverse-integer/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-231, 231 - 1]
, then return 0
.
2 |
3 |
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: x = 123
9 | Output: 321
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: x = -123
15 | Output: -321
16 |
17 |
18 |
Example 3:
19 |
20 |
Input: x = 120
21 | Output: 21
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | -231 <= x <= 231 - 1
29 |
30 |
--------------------------------------------------------------------------------
/70/ Climbing Stairs/Solution.kt:
--------------------------------------------------------------------------------
1 | package `70`.` Climbing Stairs`
2 |
3 | class Solution {
4 | fun climbStairs(n: Int): Int {
5 | val arr = MutableList(n + 2) { 0 }
6 | arr[1] = 1
7 | arr[2] = 2
8 | return (3..n).forEach { arr[it] = arr[it - 1] + arr[it - 2] }.let { arr[n] }
9 | }
10 |
11 | }
--------------------------------------------------------------------------------
/704/ Binary Search/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int search(int[] nums, int target) {
3 |
4 | int lo = 0, hi = nums.length-1;
5 |
6 | while (lo <= hi) {
7 | int mid = lo + (hi - lo) /2;
8 | if (nums[mid] == target) {
9 | return mid;
10 | }
11 | if (nums[mid] > target) {
12 | hi = mid -1;
13 | }else{
14 | lo = mid + 1;
15 | }
16 | }
17 | return -1;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/704/ Binary Search/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int search(vector &nums, int target) {
4 | int lo = 0, hi = nums.size() - 1;
5 | while (lo <= hi) {
6 | int mid = lo + ((hi - lo) >> 1);
7 | if (nums[mid] == target) {
8 | return mid;
9 | } else if (nums[mid] > target) {
10 | hi = mid - 1;
11 | } else {
12 | lo = mid + 1;
13 | }
14 | }
15 | return -1;
16 | }
17 | };
--------------------------------------------------------------------------------
/704/ Binary Search/solution.kt:
--------------------------------------------------------------------------------
1 | package `704`.` Binary Search`
2 |
3 | internal class Solution {
4 | fun search(nums: IntArray, target: Int): Int {
5 | var lo = 0
6 | var hi = nums.size - 1
7 | while (lo <= hi) {
8 | val mid = lo + (hi - lo) / 2
9 | if (nums[mid] == target) {
10 | return mid
11 | }
12 | if (nums[mid] > target) {
13 | hi = mid - 1
14 | } else {
15 | lo = mid + 1
16 | }
17 | }
18 | return -1
19 | }
20 | }
--------------------------------------------------------------------------------
/713/ Subarray Product Less Than K/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 | public int numSubarrayProductLessThanK(int[] nums, int k) {
5 | int n = nums.length;
6 | int res = 0;
7 | for (int i = 0; i < n; i++) {
8 | long t = 1;
9 | for (int j = i; j < n; j++) {
10 | t *= nums[j];
11 | if (t < k) {
12 | res++;
13 | }else break;
14 | }
15 | }
16 | return res;
17 | }
18 | }
--------------------------------------------------------------------------------
/733/ Flood Fill/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | int[] dx = {1, -1, 0, 0};
3 | int[] dy = {0, 0, 1, -1};
4 | boolean[][] visited;
5 |
6 | public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
7 | int m = image.length, n = image[0].length;
8 | visited = new boolean[m][n];
9 | dfs(image, sr, sc, image[sr][sc], newColor);
10 | return image;
11 | }
12 |
13 | private void dfs(int[][] image, int sr, int sc, int original, int newColor) {
14 | image[sr][sc] = newColor;
15 | visited[sr][sc] = true;
16 |
17 | for (int i = 0; i < 4; i++) {
18 | int x = sr + dx[i], y = sc + dy[i];
19 | if (validate(image, x, y, original)) {
20 | dfs(image, x, y, original, newColor);
21 | }
22 | }
23 | }
24 |
25 | private boolean validate(int[][] image, int x, int y, int original) {
26 | int m = image.length, n = image[0].length;
27 | return x >= 0 && x < m && y >= 0 && y < n && image[x][y] == original && !visited[x][y];
28 | }
29 | }
--------------------------------------------------------------------------------
/733/ Flood Fill/Solution.kt:
--------------------------------------------------------------------------------
1 | package `733`.` Flood Fill`
2 |
3 | class Solution {
4 | val direct = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1))
5 | fun floodFill(image: Array, sr: Int, sc: Int, newColor: Int): Array {
6 | if (image[sr][sc] == newColor) return image
7 | dfs(image, sr, sc, image[sr][sc], newColor)
8 | return image
9 | }
10 |
11 | private fun dfs(image: Array, sr: Int, sc: Int, srcColor: Int, newColor: Int) {
12 | image[sr][sc] = newColor
13 | (0 until 4).forEach { i ->
14 | val newX = sr + direct[i][0]
15 | val newY = sc + direct[i][1]
16 | if (newX in (0 until image.size) && newY in (0 until image[0].size)
17 | && image[newX][newY] == srcColor
18 | ) {
19 | floodFill(image, newX, newY, newColor)
20 | }
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/74/ Search a 2D Matrix/Solution.kt:
--------------------------------------------------------------------------------
1 | package `74`.` Search a 2D Matrix`
2 |
3 | class Solution {
4 | fun searchMatrix(matrix: Array, target: Int): Boolean {
5 | if (matrix.isNullOrEmpty() || matrix[0].isEmpty()) {
6 | return false
7 | }
8 | val targetRow = searchTargetRowIndex(matrix, target)
9 | if (targetRow == -1) {
10 | return false
11 | }
12 |
13 | return searchTargetIndex(matrix[targetRow], target) != -1
14 | }
15 |
16 | private fun searchTargetRowIndex(matrix: Array, target: Int): Int {
17 | var left = 0
18 | var right = matrix.size - 1
19 |
20 | while (left + 1 < right) {
21 | val mid = left + (right - left) / 2
22 | when {
23 | matrix[mid][0] <= target -> left = mid
24 | matrix[mid][0] > target -> right = mid
25 | }
26 | }
27 |
28 | return when {
29 | target >= matrix[right][0] -> right
30 | target >= matrix[left][0] -> left
31 | else -> -1
32 | }
33 | }
34 |
35 |
36 | private fun searchTargetIndex(nums: IntArray, target: Int): Int {
37 | if (nums.isEmpty()) {
38 | return -1
39 | }
40 | var left = 0
41 | var right = nums.size - 1
42 | while (left + 1 < right) {
43 | val mid = left + (right - left) / 2
44 | when {
45 | nums[mid] == target -> return mid
46 | nums[mid] < target -> left = mid
47 | nums[mid] > target -> right = mid
48 | }
49 | }
50 | return when (target) {
51 | nums[left] -> left
52 | nums[right] -> right
53 | else -> -1
54 | }
55 | }
56 | }
--------------------------------------------------------------------------------
/77/ Combinations/Solution.kt:
--------------------------------------------------------------------------------
1 | package `77`.` Combinations`
2 |
3 | class Solution {
4 | private val res = ArrayList>()
5 | fun combine(n: Int, k: Int): List> {
6 | if (n < 1 || k < 1 || n < k) return res
7 | combination(n, k, 1, ArrayList())
8 | return res
9 | }
10 |
11 | private fun combination(n: Int, k: Int, start: Int, list: ArrayList) {
12 | if (list.size == k) res.add(ArrayList(list))
13 | else (start..n).forEach {
14 | list.add(it)
15 | combination(n, k, it + 1, list)
16 | list.remove(it)
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/784/ Letter Case Permutation/Solution.kt:
--------------------------------------------------------------------------------
1 | package `784`.` Letter Case Permutation`
2 |
3 | import java.util.*
4 |
5 | class Solution {
6 | fun letterCasePermutation(s: String): List {
7 | val res = mutableListOf()
8 | val que = LinkedList>()
9 | que.push(Pair(s, 0))
10 | while (que.isNotEmpty()) {
11 | val per = que.peek().first
12 | val index = que.peek().second
13 | que.pop()
14 |
15 | if (!res.contains(per)) res.add(per)
16 |
17 | for (i in index until per.length) {
18 | per[i].let {
19 | if (it.isLetter()) {
20 | val newChar = if (it.isUpperCase()) it.toLowerCase() else it.toUpperCase()
21 | val new = StringBuilder(per).replace(i, i + 1, "$newChar").toString()
22 | que.push(Pair(new, i + 1))
23 | }
24 | }
25 | }
26 | }
27 | return res
28 | }
29 | }
--------------------------------------------------------------------------------
/797/ All Paths From Source to Target/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | class Solution {
5 | public List> allPathsSourceTarget(int[][] graph) {
6 | List> res = new ArrayList<>();
7 | List path = new ArrayList<>();
8 |
9 | path.add(0);
10 | deepSearch(graph, 0, path, res);
11 |
12 | return res;
13 | }
14 |
15 | public void deepSearch(int[][] graph, int index, List path, List> res) {
16 | if (index + 1 == graph.length) {
17 | res.add(new ArrayList<>(path));
18 | return;
19 | }
20 |
21 | for (int node : graph[index]) {
22 | path.add(node);
23 | deepSearch(graph, node, path, res);
24 | path.remove(path.size() - 1);
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/82/ Remove Duplicates from Sorted List II/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 | public ListNode deleteDuplicates(ListNode head) {
5 | if (head == null || head.next == null) {
6 | return head;
7 | }
8 |
9 | ListNode fakeHead = new ListNode(0, head);
10 | ListNode prev = fakeHead;
11 | ListNode curr = head;
12 | while (curr != null) {
13 | while (curr.next != null && curr.next.val == curr.val) {
14 | curr = curr.next;
15 | }
16 |
17 | if (prev.next == curr) {
18 | prev = prev.next;
19 | } else {
20 | prev.next = curr.next;
21 | }
22 | curr = curr.next;
23 | }
24 | return fakeHead.next;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/83-remove-duplicates-from-sorted-list.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode() {}
7 | * ListNode(int val) { this.val = val; }
8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 | * }
10 | */
11 | class Solution {
12 | public ListNode deleteDuplicates(ListNode head) {
13 | if(head==null || head.next==null) return head;
14 | ListNode first = head, second = first.next;
15 | while(second != null) {
16 | if(first.val == second.val) {
17 | second=second.next;
18 | first.next = second;
19 | }else{
20 | first = second;
21 | second = second.next;
22 | }
23 | }
24 | return head;
25 | }
26 | }
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: head = [1,1,2]
7 | Output: [1,2]
8 |
9 |
10 |
Example 2:
11 |

12 |
Input: head = [1,1,2,3,3]
13 | Output: [1,2,3]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | - The number of nodes in the list is in the range
[0, 300]
.
21 | -100 <= Node.val <= 100
22 | - The list is guaranteed to be sorted in ascending order.
23 |
24 |
--------------------------------------------------------------------------------
/844/ Backspace String Compare/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public boolean backspaceCompare(String s, String t) {
3 | int i = s.length() - 1, j = t.length() - 1, back;
4 | while (true) {
5 | back = 0;
6 | while (i >= 0 && (back > 0 || s.charAt(i) == '#')) {
7 | back += s.charAt(i) == '#' ? 1 : -1;
8 | i--;
9 | }
10 | back = 0;
11 | while (j >= 0 && (back > 0 || t.charAt(j) == '#')) {
12 | back += t.charAt(j) == '#' ? 1 : -1;
13 | j--;
14 | }
15 |
16 | if (i >= 0 && j >= 0 && s.charAt(i) == t.charAt(j)) {
17 | i--;
18 | j--;
19 | } else {
20 | break;
21 | }
22 | }
23 | return i == -1 && j == -1;
24 | }
25 | }
--------------------------------------------------------------------------------
/876/ Middle of the Linked List/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public ListNode middleNode(ListNode head) {
3 | ListNode slow = head;
4 | ListNode fast = head;
5 | while (fast != null && fast.next != null) {
6 | slow = slow.next;
7 | fast = fast.next.next;
8 | }
9 | return slow;
10 | }
11 | }
--------------------------------------------------------------------------------
/88/ Merge Sorted Array/Solution.kt:
--------------------------------------------------------------------------------
1 | package `88`.` Merge Sorted Array`
2 |
3 | class Solution {
4 | fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
5 |
6 | var i = m - 1
7 | var j = n - 1
8 | var k = m + n - 1
9 | while (j >= 0)
10 | nums1[k--] = if (i >= 0 && nums1[i] > nums2[j]) nums1[i--] else nums2[j--]
11 | nums1.forEach { print("$it ") }; println()
12 | }
13 | }
--------------------------------------------------------------------------------
/9/ Palindrome Number/Solution.kt:
--------------------------------------------------------------------------------
1 | package `9`.` Palindrome Number`
2 |
3 | class Solution {
4 | fun isPalindrome(x: Int): Boolean {
5 | if (x < 0) {
6 | return false
7 | }
8 |
9 | var a = IntArray(20)
10 | var cnt = 0
11 | var n = x
12 | while (n > 0) {
13 | a[cnt++] = n % 10
14 | n /= 10
15 | }
16 | for (i in 0 until cnt / 2) {
17 | if (a[i] != a[cnt - i - 1]) return false
18 | }
19 | return true
20 | }
21 | }
--------------------------------------------------------------------------------
/977. Squares of a Sorted Array/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector sortedSquares(vector &nums) {
4 | int sz = nums.size();
5 | vector ans(sz);
6 | for (int l = 0, r = sz - 1, idx = sz - 1; l <= r; --idx) {
7 | if (-nums[l] < nums[r]) {
8 | ans[idx] = nums[r] * nums[r];
9 | --r;
10 | } else {
11 | ans [idx] = nums[l] * nums[l];
12 | ++l;
13 | }
14 | }
15 | return ans;
16 | }
17 | };
--------------------------------------------------------------------------------
/994/ Rotting Oranges/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 |
3 | class Solution {
4 | public int orangesRotting(int[][] grid) {
5 | LinkedList list = new LinkedList<>();
6 | int r = grid.length, c = grid[0].length;
7 | int freshCount = 0;
8 | for (int i = 0; i < r; i++) {
9 | for (int j = 0; j < c; j++) {
10 | if (grid[i][j] == 2) list.add(new int[]{i, j});
11 | if (grid[i][j] == 1) freshCount++;
12 | }
13 | }
14 | int res = 0;
15 | while (!list.isEmpty() && freshCount != 0) {
16 | res++;
17 | int size = list.size();
18 | while (size > 0) {
19 | size--;
20 | int[] t = list.removeFirst();
21 | if (t[0] > 0 && grid[t[0] - 1][t[1]] == 1) {
22 | freshCount--;
23 | grid[t[0] - 1][t[1]] = 2;
24 | list.add(new int[]{t[0] - 1, t[1]});
25 | }
26 | if (t[0] + 1 < r && grid[t[0] + 1][t[1]] == 1) {
27 | freshCount--;
28 | grid[t[0] + 1][t[1]] = 2;
29 | list.add(new int[]{t[0] + 1, t[1]});
30 | }
31 | if (t[1] > 0 && grid[t[0]][t[1] - 1] == 1) {
32 | freshCount--;
33 | grid[t[0]][t[1] - 1] = 2;
34 | list.add(new int[]{t[0], t[1] - 1});
35 | }
36 | if (t[1] + 1 < c && grid[t[0]][t[1] + 1] == 1) {
37 | freshCount--;
38 | grid[t[0]][t[1] + 1] = 2;
39 | list.add(new int[]{t[0], t[1] + 1});
40 | }
41 | }
42 | }
43 | return freshCount == 0 ? res : -1;
44 | }
45 | }
--------------------------------------------------------------------------------
/LeetCode.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/out/production/LeetCode/189. Rotate Array/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | void rotate(vector &nums, int k) {
4 | int sz = nums.size();
5 | int step = k % sz;
6 | for (int i = 0; i < (sz - step) / 2; ++i) {
7 | swap(nums[i], nums[sz - step - 1 - i]);
8 | }
9 | for (int i = 0; i < step / 2; ++i) {
10 | swap(nums[sz - step + i], nums[sz - 1 - i]);
11 | }
12 | for (int i = 0; i < sz / 2; ++i) {
13 | swap(nums[i], nums[sz - 1 - i]);
14 | }
15 | }
16 | };
--------------------------------------------------------------------------------
/out/production/LeetCode/278/ First Bad Version/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int firstBadVersion(int n) {
4 | int l = 1, r = n;
5 | while (l < r) {
6 | int mid = l + (r - l) / 2;
7 | if (isBadVersion(mid)) {
8 | r = mid;
9 | } else {
10 | l = mid + 1;
11 | }
12 | }
13 | return r;
14 | }
15 | };
16 |
17 |
--------------------------------------------------------------------------------
/out/production/LeetCode/567/ Permutation in String/Solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool checkInclusion(string s1, string s2) {
4 | int m = s1.size(), n = s2.size();
5 | if (m > n) return false;
6 |
7 | vector cnt1(26);
8 | vector cnt2(26);
9 | for (int i = 0; i < m; ++i) {
10 | cnt1[s1[i] - 'a']++;
11 | cnt2[s2[i] - 'a']++;
12 | }
13 |
14 | if (cnt1 == cnt2) return true;
15 |
16 | for (int i = m; i < n; ++i) {
17 | cnt2[s2[i - m] - 'a']--;
18 | cnt2[s2[i] - 'a']++;
19 | if (cnt1 == cnt2) {
20 | return true;
21 | }
22 | }
23 | return false;
24 | }
25 | };
--------------------------------------------------------------------------------
/out/production/LeetCode/695. Max Area of Island/Solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxAreaOfIsland(vector > &grid) {
4 | int m = grid.size();
5 | int n = grid[0].size();
6 | int res = 0;
7 | for (int i = 0; i < m; i++)
8 | for (int j = 0; j < n; j++)
9 | if (grid[i][j] == 1)
10 | res = max(res, dfs(grid, i, j));
11 | return res;
12 | }
13 |
14 | int dfs(vector > &grid, int i, int j) {
15 | int m = grid.size();
16 | int n = grid[0].size();
17 |
18 | if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0)
19 | return 0;
20 | grid[i][j] = 0;
21 |
22 | return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) + dfs(grid, i, j + 1) + dfs(grid, i, j - 1) + 1;
23 | }
24 | };
--------------------------------------------------------------------------------
/out/production/LeetCode/704/ Binary Search/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int search(vector &nums, int target) {
4 | int lo = 0, hi = nums.size() - 1;
5 | while (lo <= hi) {
6 | int mid = lo + ((hi - lo) >> 1);
7 | if (nums[mid] == target) {
8 | return mid;
9 | } else if (nums[mid] > target) {
10 | hi = mid - 1;
11 | } else {
12 | lo = mid + 1;
13 | }
14 | }
15 | return -1;
16 | }
17 | };
--------------------------------------------------------------------------------
/out/production/LeetCode/977. Squares of a Sorted Array/solution.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector sortedSquares(vector &nums) {
4 | int sz = nums.size();
5 | vector ans(sz);
6 | for (int l = 0, r = sz - 1, idx = sz - 1; l <= r; --idx) {
7 | if (-nums[l] < nums[r]) {
8 | ans[idx] = nums[r] * nums[r];
9 | --r;
10 | } else {
11 | ans [idx] = nums[l] * nums[l];
12 | ++l;
13 | }
14 | }
15 | return ans;
16 | }
17 | };
--------------------------------------------------------------------------------