介绍
某双非鼠鼠的算法路,用的是c#,以后可能会用c++
链表
删除链表中的倒数第n个节点
力扣链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
先把链表长度Length求出来,然后循环链表,删除第Length - n个元素
特殊情况用if判断
public class Solution {
public int Length = 0;
public void GetLength(ListNode test)
{
while (test != null)
{
Length++;
test = test.next;
}
}
public ListNode RemoveNthFromEnd(ListNode head, int n) {
int index = 1;
ListNode temp = head;
GetLength(head);
int target = Length - n;
if (target == 0) return head.next;
while (temp != null)
{
if (index == target)
{
temp.next = temp.next.next;
return head;
}
temp = temp.next;
index++;
}
return head;
}
}
两两交换链表中的节点
力扣链接:24. 两两交换链表中的节点 - 力扣(LeetCode)
直接循环链表,标识是否需要交换
public class Solution {
public ListNode SwapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode temp = head;
int mark = 0;
while (temp.next != null)
{
if (mark == 1)
{
temp = temp.next;
mark = 0;
continue;
}
int change = temp.val;
temp.val = temp.next.val;
temp.next.val = change;
temp = temp.next;
mark = 1;
}
return head;
}
}
链表相交
力扣链接:面试题 02.07. 链表相交 - 力扣(LeetCode)
不太明白题目意思,所以用了最笨的方法,两个while循环,找相交的节点^v^
public class Solution {
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
ListNode tempA = headA;
while (tempA != null)
{
ListNode tempB = headB;
while (tempB != null)
{
if (tempA == tempB) return tempA;
tempB = tempB.next;
}
tempA = tempA.next;
}
return null;
}
}
//改进方法的核心代码如下
tempA = tempA == null ? headA : tempA.next;
tempB = tempB == null ? headB : tempB.next;
哈希
有效的字母异位词
力扣链接:242. 有效的字母异位词 - 力扣(LeetCode)
用dictionary字典实现哈希,key对应字符串中的每个字符,value对应出现的次数
第一次用c#的Dictionary写算法,磕磕绊绊的┭┮﹏┭┮
public class Solution {
public bool IsAnagram(string s, string t) {
Dictionary<char, int> dicA = new Dictionary<char, int>();
Dictionary<char, int> dicB = new Dictionary<char, int>();
dicA = func(s);
dicB = func(t);
foreach(char item in dicA.Keys)
{
if (!dicB.ContainsKey(item))
return false;
if (dicA[item] != dicB[item])
return false;
}
foreach(char item in dicB.Keys)
{
if (!dicA.ContainsKey(item))
return false;
if (dicB[item] != dicA[item])
return false;
}
return true;
}
public Dictionary<char, int> func(string str)
{
Dictionary<char, int> dic = new Dictionary<char, int>();
foreach(char item in str)
{
if ( !dic.ContainsKey(item) )
dic.Add(item, 1);
else
dic[item]++;
}
return dic;
}
}