leetcode notes

leetcode刷题笔记

二分搜索

二分查找

二分查找,双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right){
int mid = (left + right )/2;
if(target == nums[mid]){
return mid;
}else if(target < nums[mid]){
right = mid - 1;
}else if(target > nums[mid]){
left = mid + 1;
}
}
retur
}
}

其他

两数之和

哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashMap = new HashMap<>();
for( int i=0; i < nums.length; i++ ){
int num = nums[i];
if(hashMap.containsKey(target-num)){
return new int[]{i,hashMap.get(target-num)};
}
hashMap.put(num,i);
}
return new int[]{0};
}
}