Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Duplicates from a Sorted List #231

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
54 changes: 54 additions & 0 deletions leetcode/binary-search/SearchSortedRotatedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Given an array after the possible rotation and an integer target, return the index of target if it is in the array, or -1 if it is not in the array.

// eg Input: arr = [4,5,6,7,0,1,2], target = 0, Output: 4



class SearchRotatedSortedArray {
public int search(int[] arr, int target) {
int pivot = findPivot(arr);
if (pivot == -1) {
return binarySearch(arr, target, 0, arr.length - 1);
}
if (arr[pivot] == target) {
return pivot;
} else if (target >= arr[0]) {
return binarySearch(arr, target, 0, pivot - 1);
}
return binarySearch(arr, target, pivot + 1, arr.length - 1);
}

int binarySearch(int[] arr, int target, int start, int end) {
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}

int findPivot(int[] nums) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid < end && nums[mid] > nums[mid + 1]) {
return mid;
}
if (mid > start && nums[mid] < nums[mid - 1]) {
return mid - 1;
}
if (nums[mid] < nums[start]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}
37 changes: 37 additions & 0 deletions leetcode/linked-list/RemoveDuplicatesFromSortedList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Leetcode 83. Remove duplicates from a sorted List
* Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
* example: Input: head = [1,1,2] Output: [1,2]
*/




/**
* 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 temp = head;
while(temp.next != null){
if(temp.val == temp.next.val){
temp.next = temp.next.next;
}
else{
temp = temp.next;
}
}
return head;
}
}