Menu Sidebar
Menu

two pointers

Find the Duplicate Number

双指针. 找环 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 […]

[LintCode] Triangle Count

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 […]

[LintCode] Valid Palindrome

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’ && […]

[LintCode] Linked List Cycle

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; }

[LintCode] 3 Sum

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; […]

[LintCode] 3 Sum Closest

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 […]

[LintCode] Remove Element

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; }

书脊

这青苔碧瓦堆, 俺曾睡风流觉, 将五十年兴亡看饱.

January 2023
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031