Skip to content

Commit 6c9c785

Browse files
author
Botao Xiao
committed
[Function add]: 1. Add leetcode solutions with tag amazon.
1 parent 85a501f commit 6c9c785

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
## 387. First Unique Character in a String
2+
3+
### Question
4+
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
5+
6+
```
7+
Examples:
8+
9+
s = "leetcode"
10+
return 0.
11+
12+
s = "loveleetcode",
13+
return 2.
14+
```
15+
16+
Note: You may assume the string contain only lowercase letters.
17+
18+
### Solution
19+
* Method 1: array(or hashMap)
20+
```Java
21+
class Solution {
22+
public int firstUniqChar(String s) {
23+
int[] dic = new int[26];
24+
char[] arr = s.toCharArray();
25+
for(char c : arr){
26+
dic[c - 'a']++;
27+
}
28+
for(int i = 0; i < arr.length; i++){
29+
if(dic[arr[i] - 'a'] == 1) return i;
30+
}
31+
return -1;
32+
}
33+
}
34+
```
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
## 973. K Closest Points to Origin
2+
3+
### Question
4+
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
5+
6+
(Here, the distance between two points on a plane is the Euclidean distance.)
7+
8+
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
9+
10+
```
11+
Example 1:
12+
13+
Input: points = [[1,3],[-2,2]], K = 1
14+
Output: [[-2,2]]
15+
Explanation:
16+
The distance between (1, 3) and the origin is sqrt(10).
17+
The distance between (-2, 2) and the origin is sqrt(8).
18+
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
19+
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
20+
Example 2:
21+
22+
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
23+
Output: [[3,3],[-2,4]]
24+
(The answer [[-2,4],[3,3]] would also be accepted.)
25+
```
26+
27+
Note:
28+
1. 1 <= K <= points.length <= 10000
29+
2. -10000 < points[i][0] < 10000
30+
3. -10000 < points[i][1] < 10000
31+
32+
### Solutions:
33+
* Method 1: PriorityQueue
34+
```Java
35+
class Solution {
36+
public int[][] kClosest(int[][] points, int K) {
37+
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
38+
@Override
39+
public int compare(int[] a, int[] b){
40+
return a[0] * a[0] + a[1] * a[1] - b[0] * b[0] - b[1] * b[1];
41+
}
42+
});
43+
for(int[] point : points) pq.offer(point);
44+
int[][] res = new int[K][2];
45+
int count = 0;
46+
for(int i = 0; i < K; i++){
47+
res[i] = pq.poll();
48+
}
49+
return res;
50+
}
51+
}
52+
```

0 commit comments

Comments
 (0)