目录
1. 只出现一次的数字(LeetCode 136 题)
[只出现一次的数字 II]顺带做了 用一个方法~
1.1题目
1.2思路
构建出现数字的hashmap HashMap<Integer,Boolean> hashmap = new HashMap<>();
Integer就是我们遍历的每个数字为Key,boolean是做数字出现统计,也就是一个标志。我这里用boolean比较节约空间……
如果在hashmap中有nums[i]的数据,就可以直接删除,因为成对了。最后只留下我们唯一的一个不成对的数。
同样的,在三个数时只是把标志位改了一下,第一次为false,第二次为true,第三次remove data即可。
1.3代码
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer,Boolean> hashmap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hashmap.containsKey(nums[i])){
hashmap.remove(nums[i]);
}
else hashmap.put(nums[i],true);
}
for (int key:hashmap.keySet()) {
return key;
}
return 0;
}
}
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer,Boolean> hashmap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hashmap.containsKey(nums[i])){
if (hashmap.get(nums[i])) hashmap.remove(nums[i]);
else hashmap.replace(nums[i],true);
}
else hashmap.put(nums[i],false);
}
for (int key:hashmap.keySet()
) {
return key;
}
return 0;
}
}
2. 环形链表(LeetCode 141 题)
2.1题目
2.2思路
解法1
hash方法。每次遍历节点,然后key放入我们的ListNode,值随便放。然后每次对节点在hashmap进行k查找,如果存在return false。如果遍历结束return true。
时间复杂度,空间复杂度均为1.
/**
* 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) {
HashMap<ListNode,Boolean> hashmap = new HashMap<>();
while(head!=null){
if(hashmap.containsKey(head)){
return true;
}
else{
hashmap.put(head,true);
}
head = head.next;
}
return false;
}
}
解法二
快慢指针法。这个方法比较巧妙。首先设定指针1,为正常的遍历指针,然后设定指针2,以两步的速度遍历。如果指针二遇到null说明遍历结束,否则指针1和指针2必然相遇。意思就是如果在相同跑到一起跑步的同学,A同学速度为x,B同学速度为2X,那么AB两同学从相同起点出发必然会在途中再次相遇。时间复杂度为n,空间复杂度为1.
2.3代码
/**
* 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) {
if(head==null||head.next==null) return false;
ListNode l1 = head;
ListNode l2 = head.next;
while(l1!=l2){
if(l2!=null&&l2.next!=null){
l2 = l2.next.next;
l1 = l1.next;
}
else return false;
}
return true;
}
}
3. 环形链表 II(LeetCode 142题)
3.1题目
3.2思路
解法1
简单运用上题的方法一即可得到答案~。
3.3代码
/**
* 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) {
HashMap<ListNode,Boolean> hashmap = new HashMap<>();
while(head!=null){
if(hashmap.containsKey(head)){
return head;
}
else{
hashmap.put(head,true);
}
head = head.next;
}
return null;
}
}