Leetcode 160 169 206

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值