Duplicate Zeros
往后加一个0,然后移动其他数 看到讨论里有个o(1) time, o(n) space的, 利用queue作为结果的预存储:
往后加一个0,然后移动其他数 看到讨论里有个o(1) time, o(n) space的, 利用queue作为结果的预存储:
双指针. 找环 public class FloydsCycleDetection { public static int floyd(int[] a){ int s = a[0]; int f = a[0]; do { s = a[s]; f = a[a[f]]; } while (s!=f); s = a[0]; while (s != f){ s = a[s]; f = a[f]; } return f; } public static void main(String[] args) { int[] t […]
public int triangleCount(int S[]) { // write your code here int res = 0; if(S.length == 0 || S == null) return res; Arrays.sort(S); for(int i = S.length – 1; i > 0; i–) { int l = 0; int r = i – 1; while(l < r) { if(S[l] + S[r] > S[i]){ res […]
public boolean isPalindrome(String s) { // Write your code here if(s.length() == 0 || s == null) return true; s = s.toLowerCase(); s = s.trim(); int i = 0; int j = s.length() – 1; while(i <= j) { while(i <= j && !((s.charAt(i) <= ‘z’ && s.charAt(i) >= ‘a’) || (s.charAt(i) >= ‘0’ && […]
public boolean hasCycle(ListNode head) { // write your code here if(head == null) return false; ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; if(slow == fast) return true; } return false; }
public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { // write your code here ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(numbers.length == 0 || numbers == null) return res; Arrays.sort(numbers); for(int i = 0 ; i < numbers.length – 2; i++) { if(i != 0 && numbers[i] == numbers[i-1]) continue; int l = i+1; int r = numbers.length – 1; […]
public int threeSumClosest(int[] numbers ,int target) { // write your code here Arrays.sort(numbers); if(numbers.length == 0 || numbers == null) return 0; int close = Integer.MAX_VALUE; for(int i = 0; i < numbers.length – 2; i++) { int j = i + 1; int k = numbers.length – 1; while(j < k) { int sum […]
public int removeDuplicates(int[] nums) { // write your code here int res = 0; if(nums.length == 0 || nums == null) return res; for(int i = 1 ; i < nums.length; i++) { if(nums[res] != nums[i]){ nums[++res] = nums[i]; } } return res+1; }
public int removeElement(int[] A, int elem) { // write your code here int res = 0; if(A.length == 0 || A == null) return res; for(int i = 0 ; i < A.length; i++) { if(A[i] != elem) A[res++] = A[i]; } return res; }