1. 搜索旋转数组(81)
给你 旋转后 的数组 nums
和一个整数 target
,请你编写一个函数来判断给定的目标值是否存在于数组中。如果 nums
中存在这个目标值 target
,则返回 true
,否则返回 false
class Solution { public boolean search(int[] nums, int target) { int l=0,r=nums.length-1; if(nums.length==0) return false; if(nums.length==1) return nums[0]==target; while (l<=r){ int mid = (l+r)/2; if(nums[mid]==target) return true; if(nums[l]==nums[mid]&&nums[mid]==nums[r]){ l++; r--; }else if(nums[l]<=nums[mid]){ if(nums[l]<=target&&target<=nums[mid]){ r=mid-1; }else { l=mid+1; } }else { if(nums[mid]<target&&target<=nums[r]){ l= mid+1; }else { r=mid-1; } } } return false; } }
2.删除排序列表中的重复元素(82)
给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if (head==null) return head; ListNode dummy = new ListNode(0,head); ListNode cur =dummy; while (cur.next!=null&&cur.next.next!=null){ if(cur.next.val==cur.next.next.val){ int x= cur.next.val; while (cur.next!=null&&cur.next.val==x){ cur.next =cur.next.next; } }else { cur=cur.next; } } return dummy.next; } }
3. 删除排序列表中的重复元素(83)
给定一个已排序的链表的头 head
, 删除所有重复元素,使每个元素只出现一次 。返回已排序的链表 。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if (head==null||head.next==null) return head; ListNode cur =head; while (cur.next!=null){ if(cur.val==cur.next.val){ while (cur.next!=null&&cur.val==cur.next.val){ cur.next=cur.next.next; } }else { cur=cur.next; } } return head; } }