删除有序数组中的重复项
LeetCode地址:26. 删除有序数组中的重复项 - 力扣(LeetCode)
public int removeDuplicates(int[] nums) {
int p1=0,p2=1;
while (p2<nums.length){
if (nums[p1]==nums[p2]){
p2++;
}else {
nums[++p1]=nums[p2++];
}
}
return p1+1;
}
删除有序链表中的重复项
LeetCode地址:83. 删除排序链表中的重复元素 - 力扣(LeetCode)
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return null;
}
ListNode slow = head;
ListNode fast = head;
while(fast!=null){
if(fast.val!=slow.val){
slow.next=fast;
slow = slow.next;
}
fast = fast.next;
}
slow.next = null;
return head;
}
删除链表的倒数第 N 个结点
LeetCode地址:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode node = new ListNode(-1);
node.next = head;
ListNode slow = node;
ListNode fast = node;
for(int i = 0;i < n;i++){
fast = fast.next;
}
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return node.next;
}
相交链表
LeetCode:160. 相交链表 - 力扣(LeetCode)
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1 = headA;
ListNode p2 = headB;
while(p1!=p2){
if(p1==null){
p1=headB;
}else{
p1=p1.next;
}
if(p2==null){
p2=headA;
}else{
p2=p2.next;
}
}
return p1;
}
}
二分查找
LeetCode:704. 二分查找 - 力扣(LeetCode)
class Solution {
public int search(int[] nums, int target) {
int left=0,right=nums.length-1;
int mid = (left+right)/2;
while(left<=right){
mid=(left+right)/2;
if(target==nums[mid]){
return mid;
}else if(target>nums[mid]){
left=mid+1;
}else{
right=mid-1;
}
}
return -1;
}
}
两数之和
Leetcode:167. 两数之和 II - 输入有序数组 - 力扣(LeetCode)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l=0,r=numbers.length-1;
while(l<r){
int res = numbers[l]+numbers[r];
if(res == target){
return new int[]{l+1,r+1};
}else if(res > target){
r--;
}else{
l++;
}
}
return null;
}
}
反转字符串
Leetcode:344. 反转字符串 - 力扣(LeetCode)
class Solution {
public void reverseString(char[] s) {
int l=0,r=s.length-1;
while(l<r){
char c = s[l];
s[l++]=s[r];
s[r--]=c;
}
}
}
验证回文串
Leetcode:125. 验证回文串 - 力扣(LeetCode)
public boolean isPalindrome(String s) {
char[] arr = s.toLowerCase().toCharArray();
int l=0,r=arr.length-1;
while(l<r){
while (l<r&&!ischar(arr[l])){
l++;
}
while (l<r&&!ischar(arr[r])){
r--;
}
if (arr[l++]!=arr[r--]){
return false;
}
}
return true;
}
public boolean ischar(char c){
return (c>='0'&&c<='9')||(c>='a'&&c<='z');
}