删除链表中重复的结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return null;
}
ListNode curr=head;
while(curr!=null){
while(curr.next!=null&&curr.next.val==curr.val)
{
curr.next=curr.next.next;//curr.next不和curr相等时,循环结束,curr指向下一个节点
}
curr=curr.next;
}
return head;
}
}
curr.next指向不和curr.val不相等时,内层循环结束,curr指向下一个结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return null;
}
ListNode res=new ListNode(0);
res.next=head;
ListNode curr=head;
ListNode pre=res;
while(curr!=null){
while(curr.next!=null&&curr.val==curr.next.val){
curr=curr.next;
}
if(pre.next!=curr){
curr=curr.next;
pre.next=curr;
}else{
pre=pre.next;
curr=curr.next;
}
}
return res.next;
}
}
import java.util.*;
public class Solution {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> res=new ArrayList<Integer>();
if(n==0){
res.add(0);
return res;
}
res.add(0);
res.add(1);
for(int i=2;i<=n;i++){
int size=res.size();
for(int j=res.size()-1;j>=0;j--){
res.add(res.get(j)+(1<<(i-1))) ;
}
}
return res;
}
}
格雷码,有规律,就是在前一次的数组的基础上加的每一个元素前加0以及倒序后加1,(1<<(i-1))表示的是1向左移动i-1位。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy=new ListNode(0);
ListNode prestart=dummy;
prestart.next=head;
ListNode start=head;
for(int i=1;i<m;i++){
prestart=start;
start=start.next;
}
for(int j=0;j<n-m;j++){
ListNode temp=start.next;
start.next=temp.next;
temp.next=prestart.next;
prestart.next=temp;
}
return dummy.next;
}
}
相当于冒泡,比如 1-2-3-4-5,m=2,n=4
先将prestart=1记录下来,每次将start遍历的结点放到紧接着1的位置,比如将3放到1后面,然后将4放到1后面这样就变成14325了
public class Solution {
public int removeDuplicates(int[] A) {
int n=A.length;
if(n<=2){
return n;
}
int index=2;
for(int i=2;i<n;i++){
if(A[i]!=A[index-2]){
A[index++]=A[i];
}
}
return index;
}
}
public class Solution {
public int removeDuplicates(int[] A) {
int n=A.length;
if(n<=2){
return n;
}
int index=0;
int count=0;
for(int i=1;i<n;i++){
if(A[index]!=A[i]){
A[++index]=A[i];
count=0;
}else{
count++;
if(count<2){
A[++index]=A[i];
}
}
}
return index+1;
}
}