Skip to content

Commit

Permalink
feat(leetcode): #12, study the No0167 and No0283
Browse files Browse the repository at this point in the history
  • Loading branch information
llama90 committed Jun 3, 2022
1 parent 17e411a commit a787edd
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 0 deletions.
25 changes: 25 additions & 0 deletions leetcode/src/main/java/com/github/lucaseo90/easy/No0283.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.github.lucaseo90.easy;

public class No0283 {
public int[] moveZeros(int[] nums) {
int left = 0;
int right = 1;
while (right < nums.length) {
if (nums[left] != 0) {
left++;
right++;
} else if (nums[right] == 0) {
right++;
} else {
swap(nums, left, right);
}
}
return nums;
}

private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
21 changes: 21 additions & 0 deletions leetcode/src/main/java/com/github/lucaseo90/medium/No0167.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.github.lucaseo90.medium;

public class No0167 {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;

while (left < right) {
if (numbers[left] + numbers[right] == target) {
break;
}
if (numbers[left] < (target - numbers[right])) {
left++;
} else {
right--;
}
}

return new int[]{left + 1, right + 1};
}
}
22 changes: 22 additions & 0 deletions leetcode/src/test/java/com/github/lucaseo90/easy/No0283Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.github.lucaseo90.easy;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;

public class No0283Test {

No0283 no0283 = new No0283();

@Test
public void testExample01() {
Assert.assertEquals("[1, 3, 12, 0, 0]", Arrays.toString(no0283.moveZeros(new int[]{0, 1, 0, 3, 12})));
}

@Test
public void testExample02() {
Assert.assertEquals("[0]", Arrays.toString(no0283.moveZeros(new int[]{0})));
}

}
27 changes: 27 additions & 0 deletions leetcode/src/test/java/com/github/lucaseo90/medium/No0167Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.github.lucaseo90.medium;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;

public class No0167Test {

No0167 no0167 = new No0167();

@Test
public void testExample01() {
Assert.assertEquals("[1, 2]", Arrays.toString(no0167.twoSum(new int[]{2, 7, 11, 15}, 9)));
}

@Test
public void testExample02() {
Assert.assertEquals("[1, 3]", Arrays.toString(no0167.twoSum(new int[]{2, 3, 4}, 6)));
}

@Test
public void testExample03() {
Assert.assertEquals("[1, 2]", Arrays.toString(no0167.twoSum(new int[]{-1, 0}, -1)));
}

}

0 comments on commit a787edd

Please sign in to comment.