1.两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int searchNum = target - nums[i];
if(map.containsKey(searchNum)){
return new int[]{map.get(searchNum), i};
}
map.put(nums[i], i);
}
return null;
}
}
15.三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//数组长度
int len = nums.length;
//结果集
List<List<Integer>> result = new ArrayList<>();
//对数组进行排序
Arrays.sort(nums);
//遍历每一个元素
for(int i = 0; i < len; i++){
//当前数大于0直接退出循环
if(nums[i] > 0) break;
//如果当前数重复直接跳过
if(i > 0 && nums[i] == nums[i-1]) continue;
//左指针
int lp = i + 1;
//右指针
int rp = len - 1;
//当左右指针不重叠时,可以移动指针
while(lp < rp){
int sum = nums[i] + nums[lp] + nums[rp];
if(sum == 0){
result.add(Arrays.asList(nums[i], nums[lp], nums[rp]));
lp++;
rp--;
//跳过连续重复的元素
while(lp < rp && nums[lp] == nums[lp-1]) lp++;
while(lp < rp && nums[rp] == nums[rp+1]) rp--;
}else if(sum < 0){
lp++;
}else{
rp--;
}
}
}
return result;
}
}
19.删除链表的倒数第N个结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode sentinel = new ListNode(-1, head);
ListNode front = sentinel;
ListNode back = sentinel;
for(int i = 0; i < n+1; i++){
front = front.next;
}
while(front != null){
front = front.next;
back = back.next;
}
back.next = back.next.next;
return sentinel.next;
}
}