160.相交链表
题目描述:编写一个程序,找到两个单链表相交的起始节点。
思路:采用集合的方式即可。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
HashSet<ListNode> hset=new HashSet<ListNode>();
ListNode temp=headA;
while(temp!=null)
{
hset.Add(temp);
temp=temp.next;
}
temp=headB;
while(temp!=null)
{
if(hset.Contains(temp))
return temp;
temp=temp.next;
}
return null;
}
}
169.多数元素
题目描述:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
思路:利用Boyer-Moore 投票算法,先假设第一个元素就是这个众数,初始化count为1,遇上众数则count加一,否则减一。中间如果count为0,则说明前面的元素个数众数和不是众数正好相等抵消了,更换新的众数,继续以上的方法。
代码如下:
public class Solution {
public int MajorityElement(int[] nums) {
int can=nums[0];
int count=1;
for(int i=1;i<nums.Length;i++)
{
if(count==0)
can=nums[i];
count+=(nums[i]==can)?1:-1;
}
return can;
}
}
206.反转链表
题目描述:反转一个单链表。
思路:使用三个结点进行操作即可,关键在于注意更换每个结点时的顺序。
代码如下:
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode phead=head;
ListNode ptemp=null;
while(phead!=null)
{
ListNode temp=phead.next;
phead.next=ptemp;
ptemp=phead;
phead=temp;
}
return ptemp;
}
}