目录
* 两数之和 https://leetcode-cn.com/problems/two-sum/
* 判断链表是否有环 https://leetcode-cn.com/problems/linked-list-cycle/
* ==*三数之和== https://leetcode-cn.com/problems/3sum/
* 环形链表2 https://leetcode-cn.com/problems/linked-list-cycle-ii/
1. 算法题
简单
* 两数之和 https://leetcode-cn.com/problems/two-sum/
class Solution {
public int[] twoSum(int[] nums, int target) {
//1.获取数组长度
int len = nums.length;
//2.构建hash表
Map<Integer,Integer> hashMap = new HashMap<>(len - 1);
//3.第一个数肯定在哈希表中
hashMap.put(nums[0],0);
//4.从第二个数开始循环遍历,在Hash表中找出它的taget值
for (int i = 1; i < len; i++) {
//在hash表中存在就取出来
if (hashMap.containsKey(target - nums[i]))
{
return new int[]{hashMap.get(target - nums[i]),i};
}
//5.不存在就添加进hash表
hashMap.put(nums[i],i);
}
throw new RuntimeException("不存在两数之和");
}
}
* 判断链表是否有环 https://leetcode-cn.com/problems/linked-list-cycle/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
//1.首先创建一个哈希表用于保存已经访问过得
Set<ListNode> set = new HashSet<ListNode>();
//2.当链表不为空时
while(head != null)
{
//3.遍历并判断是否添加成功
if(!set.add(head))
{
//4.添加失败,返回true,说明是个环形链表
return true;
}
//5.添加成功的话,则一直往后面遍历
head = head.next;
}
//6.遍历完,还没有找到和哈希表中相同的数据则返回false
return false;
}
}
中等
* ==*三数之和== https://leetcode-cn.com/problems/3sum/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//1.创建ArrayList对象,用于返回
List<List<Integer>> ans = new ArrayList<>();
//2.获取数组长度,判空校验
int len = nums.length;
if (nums == null || nums.length < 3) return ans;
//3.将数组进行排序
Arrays.sort(nums);
//4.循环遍历
for (int i = 0; i < len; i++) {
//5.如果当前数字大于0,则三数之和一定大于0,所以循环结束
if (nums[i] > 0) break;
//6.去重
if (i > 0 && nums[i] == nums[i - 1]) continue;//去重
//7.双边指针,L = i + 1,R = len - 1.
int L = i + 1;
int R = len - 1;
//8.双边循环,L >= R就退出
while (L < R)
{
//9.计算三数之和
int sum = nums[i] + nums[L] + nums[R];
//10.判断nums是否等于0
if (sum == 0)
{
//11.添加到List集合里面
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
//12.进行双指针的前后去重
while (L < R && nums[L] == nums[L+1]) L++;
while (L < R && nums[R] == nums[R-1]) R--;
L++;
R--;
}
//13.说明左指针指的数和i位置的相加的负数太大
else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return ans;
}
}
* 环形链表2 https://leetcode-cn.com/problems/linked-list-cycle-ii/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
//1.首先创建一个哈希表
Set<ListNode> set = new HashSet<ListNode>();
//2.用一个临时节点去保存当前节点
ListNode tempNode = head;
//3.遍历当前链表
while(tempNode != null){
//5.判断当前哈希表是否包含遍历的节点
if(set.contains(tempNode))
{
return tempNode;
}else
{
set.add(tempNode);
}
tempNode = tempNode.next;
}
//4.无环返回null
return null;
}
}
2. 创建一个对象的详细流程?(JVM相关)
- 加载.class文件,执行类加载过程
- 栈内存开辟内存空间,存放对象的引用变量p
- 堆内存开辟内存空间,存放对象
- 对成员变量进行默认初始化
- 对成员变量进行显示初始化
- 执行构造方法
- 堆内存完成
- 把堆内存的地址赋值给引用变量p