basic data structures

 

content

1. Intersection of two numbers

2. The best time to buy and sell stocks

3. Merge two arrays


1. Intersection of two numbers

350. Intersection of Two Arrays II - LeetCode (leetcode-cn.com) icon-default.png?t=M1L8https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/

Topics and examples:

 Problem-solving ideas ①: (using sets to solve problems)

①Store the number in nums1 into list1

② Determine whether the number in nums2 exists in list1, and if so, store the number in list2

③ At the same time, delete the number in list1

code show as below:

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
List<Integer>list1=new ArrayList<>();
List<Integer>list2=new ArrayList<>();
for(int i=0;i<nums1.length;i++){
    list1.add(nums1[i]);
}  
 for (int num : nums2) {
            if (list1.contains(num)) {
                list2.add(num);
                // 从 list1 除去已匹配的数值
                list1.remove(Integer.valueOf(num));
            }
        }
int []tmp=new int [list2.size()];
int m=0;
for(int nums:list2){
    tmp[m++]=nums;
}return tmp;
}
    }

Problem-solving idea ②: (using hash map to solve the problem)

①Compare the lengths of nums1 and nums2, if nums1.length<nums2.length, then exchange the two arrays

②Using the correspondence between the two values ​​of Map<key,value>, store each element in nums1 into the hash Map, count with count=value, if the same key appears, count++;

③Use tmp=0; to record the subscript in the intersection

④ Traverse the array nums2, if there is an element contained in nums1, and the count>0 represented by it, copy the element to num1[tmp], and at the same time let tmp++ point to the next bit.

⑤ Let count--; reduce the number of times it appears in HashMap

⑥ Return the first k elements of nums1

The code is as follows: (The code segment has detailed comments for reference)

class Solution {
//交换数组的判断
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
//创建HashMap,并将nums1中的数存入其中
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int num : nums1) {
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
        }
//创建一个新的等同nums1大小的数组
        int[] intersection = new int[nums1.length];
        int index = 0;
//判断在nums2中的数是否出现在HashMap中,并执行对应的方法
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0) {
                intersection[index++] = num;
                count--;
                if (count > 0) {
                    map.put(num, count);
                } else {
                    map.remove(num);
                }
            }
        }
//从下标from开始复制,复制到上标to,生成一个新的数组。注意这里包括下标from,不包括上标to。
        return Arrays.copyOfRange(intersection, 0, index);
    }
}

2. The best time to buy and sell stocks

121. Best time to buy and sell stocks - LeetCode (leetcode-cn.com) icon-default.png?t=M1L8https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

Topics and examples:

 Problem-solving ideas ①: (use the set method to solve)

Because the worst here may be 0, and the calculation is required to be the best case, the element non-repeatability of the set can be ignored here to complete

①Using the brute force solution, double loop, add each difference to the set

②When set is not equal to empty, directly use Collection.max(set) to find the maximum value in the set, because it is a reference value, so it needs to be unboxed and then returned

code show as below:

class Solution {
    public static int maxProfit(int[] prices) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[i] < prices[j]) {
                    int m = prices[j] - prices[i];
                    set.add(m);
                }
            }
        }
        if (!set.isEmpty()) {
            Integer res = Collections.max(set);
            return res;
        } else {
            return 0;
        }
    }

Problem-solving ideas ②: (using dp dynamic programming to solve the problem)

①Find the minimum value before buying today

②Calculate the maximum profit of selling today

③Compare daily profits and get the maximum value

code show as below:

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1)
            return 0;
        int min = prices[0], max = 0;
        for(int i = 1; i < prices.length; i++) {
            max = Math.max(max, prices[i] - min);
            min = Math.min(min, prices[i]);
        }
        return max;
    }
}

3. Merge two arrays

88. Merge Two Sorted Arrays - LeetCode (leetcode-cn.com) icon-default.png?t=M1L8https://leetcode-cn.com/problems/merge-sorted-array/ 

Topics and examples:

Problem-solving ideas: (In the previous sorting (2), there is an explanation in the merge sort)

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int s1=0;
        int e1=m-1;
        int s2=0;
        int e2=n-1;
        int index=0;
        int []tmp=new int[m+n];
        while (s1 <= e1 && s2 <= e2) {
            if(nums1[s1] <= nums2[s2]) {
                tmp[index] = nums1[s1];
                index++;
                s1++;
            }else {
                tmp[index] = nums2[s2];
                index++;
                s2++;
            }
        }
//此时表示s2数组已经走完,把剩下的s1数组中的数依次放入合并的数组中即可
        while (s1 <= e1) {
            tmp[index++] = nums1[s1++];
            //此处也可以像上面那样写成index++;s1++;
        }
//此时表示s1数组已经走完,把剩下的s2数组中的数依次放入合并的数组中即可
        while (s2 <= e2) {
            tmp[index++] = nums2[s2++];
        }
       for(int i=0;i<m+n;i++){
        nums1[i]=tmp[i];
       }
    }
    }

Come on duck~

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/123315953
Recommended