Count the number of occurrences of a certain number in an array

Count the number of occurrences of a certain number in an array

Ideas

This is relatively simple. The idea is actually to traverse all the numbers in the array and compare them. If there are any, just record them. But in the past few days, I saw a two-way list LinkList method, so I took it out for comparison.

accomplish

Ordinary array methods

    /// <summary>
    /// 数组比较出现次数(int)
    /// </summary>
    /// <param name="arr"></param>
    /// <param name="number"></param>
    /// <returns></returns>
    int GetNumCount(int[] arr,int number)
    {
    
    
        int count = 0;
        for (int i = 0; i < arr.Length; i++)
        {
    
    
            if (arr[i] == number)
            {
    
    
                count++;
            }
        }
        return count;
    }

Two-way list method

/// <summary>
    /// 双向链表比较出现次数(int)
    /// </summary>
    /// <param name="arr"></param>
    /// <param name="number"></param>
    /// <returns></returns>
    int GetNumCountLinkedList(int[] arr, int number)
    {
    
    
        int count = 0;
        LinkedList<int> numbers = new LinkedList<int>(arr);
        int givenInt = 1;

        LinkedListNode<int> currentNode = numbers.First;
        while (currentNode != null)
        {
    
    
            if (currentNode.Value == givenInt)
            {
    
    
                count++;
            }
            currentNode = currentNode.Next;
        }
        return count;
    }

Comparison: Both can implement the above methods, but for the array method, we need to manually find the next one in the array. But the two-way list is different. It has a separate LinkedList holding class LinkedListNode, which provides us with it. Convenient for quickly finding the previous and next value.

Insert image description here

Insert image description here

Summarize

Here LinkedList only introduces usage, and the performance analysis is placed below to compare with ArrayList to analyze performance and underlying implementation.

Guess you like

Origin blog.csdn.net/qq_42194657/article/details/135438305