跳到主要內容

發表文章

目前顯示的是有「LeetCode」標籤的文章

[Leetcode] 21. Merge Two Sorted Lists

題目 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 看完題目, 以為可以用 LinkedList 這類的東西, 想說 ez ... 結果下面給的 hint Sample 根本就不是那麼一回事啊, 抓頭抓抓抓... /** * Definition for singly-linked list. * */ public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } 先拿到測試資料 /** * Created by jerry on 2017/9/24. * * Merge two sorted linked lists and return it as a new list. * The new list should be made by splicing together the nodes of the first two lists. */ public class LeetCode21MergeTwoSortedListsTest { private LeetCode21MergeTwoSortedLists sol = new LeetCode21MergeTwoSortedLists(); @Test public void test1() { final ListNode l1 = null; final ListNode l2 = new ListNode(0); ListNode act = sol.mergeTwoLists(l1, l2); Assert.assertEquals(0, act.val); } @Test public void test2() { final ListNode l1 = new ListNod...

[Leetcode] 1. TwoSum

建立測試案例 public class LeetCode1TwoSumTest { final LeetCode1TwoSum twoSum = new LeetCode1TwoSum(); /** * Example: * Given nums = [2, 7, 11, 15], target = 9, * Because nums[0] + nums[1] = 2 + 7 = 9, * return [0, 1]. */ @Test public void test1() { final int[] nums = new int[]{2, 7, 11, 15}; final int target = 9; int[] act = twoSum.twoSum(nums, target); Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 0)); Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 1)); } @Test public void test2() { final int[] nums = new int[]{3, 3}; final int target = 6; int[] act = twoSum.twoSum(nums, target); Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 0)); Assert.assertTrue(IntStream.of(act).anyMatch(x -> x == 1)); } @Test public void test3() { final int[] nums = new int[]{3, 2, 4}; final int target = 6; ...

Java Swap 的黑魔法

通常在做swap 都會用另外一個變數來處理交換的問題, 但其實若只做單純的 int 交換, 可以考慮用下面的黑魔法... /** * Created by jerry on 2016/11/30. */ public class Swap { public static void main(String[] args) { int a = -10; int b = 20; // magic a = a ^ b; b = a ^ b; a = a ^ b; System.out.println(a); System.out.println(b); } }