Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details

preface

This is the first question in Biweekly Contest 73, difficulty Eazy, which examines the manipulation of lists and the use of counters.

describe

You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that:

  • 0 <= i <= nums.length – 2,
  • nums[i] == key and,
  • nums[i + 1] == target.

Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.

Example 1:

Input: nums = [1,100,200,1,100], key = 1
Output: 100
Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.
No other integers follow an occurrence of key, so we return 100.
Copy the code

Note:

2 <= nums.length <= 1000
1 <= nums[i] <= 1000
The test cases will be generated such that the answer is unique.
Copy the code

parsing

I have to make fun of the first question, I don’t know who is the genius of it, I just couldn’t understand what the English description of the question was, and finally I couldn’t combine the examples and tried to do the question, I made mistakes twice before I understood what the question was about, I was really drunk.

In a list of integers with an index of 0, nums is given a key that must be the same as numS, and numS is given a key that must be the same as numS, and numS is given a key that must be the same as numS. Oh, my God, it’s still a little hard to decipher that.

Nums [I +1] = len(nums)-1 = len(nums)-1 = len(nums)-1 = len(nums)-1 = len(nums)-1 = len(nums)-1 Finally, you just count with the function Counter to find the most elements.

The time complexity is O(N), and the space complexity is O(N).

answer

class Solution(object):
    def mostFrequent(self, nums, key):
        """
        :type nums: List[int]
        :type key: int
        :rtype: int
        """
        result = []
        for i, c in enumerate(nums):
            if c == key and i+1<len(nums):
                result.append(nums[i+1])
        return collections.Counter(result).most_common()[0][0]	
Copy the code

The results

94/94 Test cases passed. Status: Accepted Runtime: 114 MS Memory Usage: 13.8 MBCopy the code

The original link

Leetcode.com/contest/biw…

Your support is my biggest motivation