1. 算法题
简单
* 两数之和
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("不存在两数之和");
}
}
* 链表是否有环
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;
}
中等
* ==*三数之和==
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
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文件将类的元信息加载到JVM内存中,放到方法区(1.7之前是堆中永久代,1.8之后元空间),并且通过classloader将字节码常量池加载到内存中,存储在方法区的运行时常量池中。
iabl =2)。
先向堆中申请一块内存区域并构建对象,同时对成员变量进行默认赋值。执行构造方法。最后将虚拟机栈中的对象引用指向堆中存储的地址。