您的位置:首页 > 其它

linked-list-cycle&&find-peak-element&&intersection-of-two-linked-lists

2015-11-15 23:08 453 查看
1、带环链表

给定一个链表,判断它是否有环。不要使用额外的空间

这道题的详解可见http://articles.leetcode.com/2010/09/detecting-loop-in-singly-linked-list.html

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
// write your code here
ListNode fast,slow;
fast = head;
slow = head;
while(fast!=null && (fast.next!=null)){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}


2、寻找峰值

你给出一个整数数组(size为n),其具有以下特点:

相邻位置的数字是不同的

A[0] < A[1] 并且 A[n - 2] > A[n - 1]

假定P是峰值的位置则满足
A[P] > A[P-1]
A[P] > A[P+1]
,返回数组中任意一个峰值的位置。

这道题太简单了,有没有。。。。感觉是我目前在平台上刷到的最简单的题。。。

class Solution {
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
public int findPeak(int[] A) {
// write your code here
for ( int  i=1 ; i<A.length-1 ; i++ ) {
if( A[i]>A[i-1]&&A[i]>A[i+1] ){
return i;
}
}
return 0;
}
}


3、两个链表的交叉

样例

下列两个链表:

A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3

在节点 c1 开始交叉。

注意

如果两个链表没有交叉,返回
null


在返回结果后,两个链表仍须保持原有的结构。

可假定整个链表结构中没有循环。

挑战

需满足 O(n) 时间复杂度,且仅用 O(1) 内存。

public class Solution {
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// Write your code here
if(headA ==null || headB == null )   return null;
int lenA = length(headA);//java中支持对数组调用.length直接计算长度,但是链表需要自己单独写。
int lenB = length(headB);
while(lenA > lenB ){
headA = headA.next;
lenA--;
}
while(lenA < lenB ){
headB = headB.next;
lenB--;
}
while(headA != headB ){
headA = headA.next;
headB = headB.next;
}
return headA;
}
public int length(ListNode n){
if(n==null) return 0;
int length = 1;
while(n.next != null ){
length ++;
n=n.next;
}
return length;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: