Leetcode Exercises

This is a leetcode algorithm list for me to track my thought and solutions.

1. Two-Sum

Problem Description: 1. Two-Sum

1.1. Golang

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func twoSum(nums []int, target int) []int {
size := len(nums)
for i := 0; i < size; i++ {
for j := i + 1; j < size; j++ {
if nums[i] + nums[j] == target {
result := []int{i, j}
sort.Slice(result, func(i, j int) bool {
return result[i] <= result[j]
})
return result
}
}
}
return []int{0, 0}
}

1.2. Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int[] twoSum(int[] numbers, int target) {
int [] res = new int[2];
if(numbers==null||numbers.length<2)
return res;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < numbers.length; i++){
if(!map.containsKey(target-numbers[i])){
map.put(numbers[i],i);
}else{
res[0]= map.get(target-numbers[i]);
res[1]= i;
break;
}
}
return res;
}
}

2. Path Sum

Problem Description: 112. Path Sum

2.1. Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/*
Test if there is a path from current node to leaf node
*/
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left == null && root.right == null) {
if (sum == root.val) return true;
else return false;
}
sum = sum - root.val; // take value from current root node
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
}

3. Reverse Words in a String

Problem Description: 151. Reverse Words in a String

3.1. Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {

public String reverseWords(String s) {
s = s.trim();
if(s.equals("")) return "";
String[] str_arr = s.split("\\s+");
StringBuilder sb = new StringBuilder("");
for(int i = str_arr.length-1; i>0; i--) {
sb.append(str_arr[i] + " ");
}
sb.append(str_arr[0]);
return sb.toString();
}
}

4. Combine Two Tables

Problem Description: 175. Combine Two Tables

4.1. MySQL

1
2
3
4
5
# Write your MySQL query statement below
select p.FirstName, p.LastName, a.City, a.State from Person as p
left join Address as a
on
p.PersonId = a.PersonId;

5. Fizz Buzz

Problem Description: 412. Fizz Buzz

5.1. Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
private boolean multiple(int i, int modValue){
return i%modValue==0;
}
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList();
for(int i = 1;i <= n;i++) {
String str = String.valueOf(i);
if(multiple(i,3) && multiple(i,5)) {
list.add("FizzBuzz");
}
else if(multiple(i,3) && !multiple(i,5)) {
list.add("Fizz");
}
else if(!multiple(i,3) && multiple(i,5)) {
list.add("Buzz");
}
else {
list.add(str);
}
}
return list;

}
}
0%