16.11.5
来源:互联网 发布:苹果怎么连不上4g网络 编辑:程序博客网 时间:2024/06/06 05:17
203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6 Return:
1 –> 2 –> 3 –> 4 –> 5
分析:删除链表中特定值的链表节点
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode removeElements(ListNode head, int val) { //当头指针为空时,返回null if(head==null)return null; //创建一个慢的指针,指向head节点 ListNode slow=new ListNode(0); slow.next=head; //标记头指针的位置 ListNode record=slow; //创建一个快指针指向头结点 ListNode fast=head; while(fast!=null){ if(fast.val==val){ //如果快指针指向的节点val与给定的值相等,则将其删除 slow.next=fast.next; fast=fast.next; }else{ //否则继续向后移动 fast=fast.next; slow=slow.next; } } //返回头指针 return record.next; }}
206. Reverse Linked List
Reverse a singly linked list.
分析:将一个链表原地逆转
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseList(ListNode head) { //当头指针为空时返回null if(head==null)return null; //创建一个新的节点用来存放逆序的链表 ListNode L=new ListNode(0); //获取原链表的头结点 ListNode p=head; ListNode temp=null; L.next=null; while(p!=null){ //先将下一个节点给temp保存,p节点用于实现头插法 temp=p.next; //头插法 p.next=L.next; L.next=p; p=temp; } //返回头结点 return L.next; }}
204. Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n.
分析:返回n范围内素数的个数
public class Solution { public int countPrimes(int n) { int[] a=new int[n+1]; int count=0; a[0]=0; if(n!=0)a[1]=0; for(int i=2;i<n;i++){ a[i]=1; } //1代表该索引是素数 for(int i=2;i*i<=n;i++){ if(a[i]==1){ for(int j=i*2;j<=n;j=i+j){ if(j%i==0){ //j不是素数 a[j]=0; } } } } //统计素数的个数 for(int i=0;i<n;i++){ if(a[i]==1){ count++; } } return count; }}
0 0
- 16.11.5
- 苏嵌5 16.11.3
- 苏嵌7 16.11.5
- 16.11.5C组总结
- 苏嵌6(补) 16.11.5
- 16.11.1
- 16.11.2
- 16.11.3
- 16.11.4
- 16.11.7
- 16.11.8
- 16.11.9
- 16.11.10
- 16.11.11
- 16.11.12
- 16.11.24
- 16.11.25
- 16.11.28
- fflush不能强制刷新到磁盘
- ThinkPHP框架IndexController中构造函数__construct导致的相关问题
- ios 从URL中截取所包含的参数,并且以字典的形式返回
- 边界不对称性
- Django & webpack & Docker & Apache 实践修正
- 16.11.5
- foo1
- String Task
- js数组的操作
- SpringDataJpa增删改查
- 随机抽样一致性(RANSAC: Random Sample Consensus)
- GitHub for Windows 安装失败,An error occurred attempting to install github 的解决办法
- 如何开始你的第一个android tango AR应用(上)
- 关于jsTree 的一些常用的用法