diff --git a/leetcode/binary-search/SearchSortedRotatedArray.java b/leetcode/binary-search/SearchSortedRotatedArray.java new file mode 100644 index 00000000..5d3266c6 --- /dev/null +++ b/leetcode/binary-search/SearchSortedRotatedArray.java @@ -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; + } +} \ No newline at end of file diff --git a/leetcode/linked-list/RemoveDuplicatesFromSortedList.java b/leetcode/linked-list/RemoveDuplicatesFromSortedList.java new file mode 100644 index 00000000..e0affa43 --- /dev/null +++ b/leetcode/linked-list/RemoveDuplicatesFromSortedList.java @@ -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; + } + } \ No newline at end of file