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
2、寻找峰值
你给出一个整数数组(size为n),其具有以下特点:
相邻位置的数字是不同的
A[0] < A[1] 并且 A[n - 2] > A[n - 1]
假定P是峰值的位置则满足
这道题太简单了,有没有。。。。感觉是我目前在平台上刷到的最简单的题。。。
3、两个链表的交叉
样例
下列两个链表:
在节点 c1 开始交叉。
注意
如果两个链表没有交叉,返回
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
挑战
需满足 O(n) 时间复杂度,且仅用 O(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; } }
相关文章推荐
- leetcode Container With Most Water python
- Java输入输出流
- Android问题集锦之四十六:改包名后出现Error type 3
- android-Ultra-Pull-To-Refresh 源码解析
- EasyUI+JQuery轻松实现步骤条效果
- 用C/C++来实现 Node.js 的模块(下)
- (spring-第4回【IoC基础篇】)spring基于注解的配置
- LeetCode Range Sum Query - Immutable
- SSH框架问题记录
- angular.animation的使用
- android 与struts 使用HttpsUrlConnection进行数据(文件/字符)传送 (客户端例)
- Swift中数组(Arrary)及成员方法介绍
- ASC Unicode UTF-8 in python
- 45天的坚持是否值得----结束篇
- OPEN CASCADE Curve Continuity
- defconfig 获得原厂config配置文件后处理
- Eclipse 配置svn
- Android Studio的使用(十一)--每次打开时选择项目,而不是直接进入上次项目
- 关系数据库设计范式介绍
- 分组报文,协议和Socket的概念