leetcode [#204] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (14)
目录1. 题目2. 解决方案3. 注意事项
题目Count the number of prime numbers less than a non-negative number, n.
解决方案12345678910111213141516171819public class Solution {    public int countPrimes(int n) {        if(n <= 2) return 0;        int count = 0;        boolean[] primeNum = new boolean[n+1];        for(int k = 2; k <= n; k++) primeNum[k] = true;        for(int i = 2; i <= Math.sqrt(n); i++){            if(!primeNum[i]) continue;            for(int j = i * i; j < n; j += i){                primeNum[j] = f...阅读全文

leetcode [#21] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (13)
目录1. 题目2. 解决方案3. 注意事项
题目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.
解决方案1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        i...阅读全文

leetcode [#217] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (15)
目录1. 题目2. 解决方案3. 注意事项
题目Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
解决方案123456789101112131415public class Solution {    public boolean containsDuplicate(int[] nums) {        int N = nums.length;        if(nums == null || N == 0) return false;        Arrays.sort(nums);        boolean result = false;        for(int k = 0; k < N-1; ...阅读全文

leetcode [#219] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (12)
目录1. 题目2. 解决方案3. 注意事项
题目Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
解决方案12345678910111213public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        int N = nums.length;        if(nums == null || N == 0) return false;        Set<Integer> set = new HashSet<Integer>();        for(int i = 0; i < nums.length; i++){     ...阅读全文

leetcode [#225] | GCidea's blog

作者:JerryXia | 发表于 , 阅读 (11)
目录1. 题目2. 解决方案3. 注意事项
题目Implement the following operations of a stack using queues.
push(x) – Push element x onto stack.pop() – Removes the element on top of the stack.top() – Get the top element.empty() – Return whether the stack is empty.Note
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or ...阅读全文