1月Leetcode刷题记录

初步结果:通过 49 ms

第一种方法相当于用了两个for循环,暴力搜索,时间复杂度O(n^{2}

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        int [] index = new int[2];
        for (int i = 0; i < length; i++) {
            for (int j = i+1; j <length ; j++) {
                if (nums[i]+nums[j]==target){
                    index[0] = i;
                    index[1] = j;
                }

            }
        }
        return index;
    }
}

第二种方法:善用哈希表(这里数组数据如果特别大的话,但此题里并不涉及排序、最大最小值等)

通过 4ms

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],i);

        }
        for(int i=0;i<nums.length;i++){
            int deter = target - nums[i];
            if(map.containsKey(deter) &&map.get(deter) != i){
                return new int [] {i,map.get(deter)};
            }
        }
        throw new IllegalArgumentException("No two sum solution"); 
    }
}

2.

方法一:时间复杂度为O(NlogN),没排序我就给你排序,先调用Array.sort()对数组进行排序,再输出倒数第K个元素,注意JAVA中倒数第K个元素的表达,是不可以用Nums.[-k]表示的

import java.util.Arrays;
class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length-k];
    }
}

方法二:

使用堆来排序,输出升序排序后的倒数第K个元素,堆的大小最大为K,并且为最小堆,这下依次将元素放入堆中,当堆满的时候,就将堆中最小元素推出。这里有个疑问(n1,n2) -> n1 - n2 为什么能控制这个堆是最小堆?

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> heap = 
        new PriorityQueue<Integer>((n1,n2) -> n1 - n2);
        for(int n:nums){
            heap.add(n);
            if (heap.size() > k){
                heap.poll();
            }
        }
        return heap.poll();  
    }
}
发布了30 篇原创文章 · 获赞 29 · 访问量 2218

猜你喜欢

转载自blog.csdn.net/weixin_41938314/article/details/103881357