如何在不使用哈希表的前提下优化移除出现奇数次数字的C#代码?
Nice job getting your initial solution up and running! Since you're focusing on linear data structures right now, let's figure out how to optimize this code without relying on hash tables—we can do this by leaning into sorting and a single-pass traversal, which will make the solution much more efficient.
First, Let's Break Down the Current Code's Limitations
Your current implementation works, but it has some key efficiency bottlenecks:
- The nested
forloops inCheckIfOddCountmean you're scanning the entire list for every single element—this gives a time complexity of O(n²), which gets slow quickly as your input list grows. - Every time you remove an element, you reset the outer loop index to 0, forcing you to re-scan the list over and over again.
- Modifying the original list while iterating over it can lead to unexpected behavior (like skipping elements or counting incorrectly).
Optimized Approach: Sort First, Then Traverse
Here's a better strategy that plays to linear data structure strengths:
- Sort the list: When sorted, all identical numbers will be grouped together. This lets us count occurrences in a single pass instead of nested loops.
- Traverse once to count and filter: As we go through the sorted list, we'll track how many times each number appears. If a number shows up an even number of times, we keep all its occurrences; if odd, we discard all of them.
Here's the optimized FilterEvenOccurrences method you can use:
public static List<int> FilterEvenOccurrences(List<int> inputList) { if (inputList == null || inputList.Count == 0) return new List<int>(); // Sort the list to group identical numbers together inputList.Sort(); List<int> filteredList = new List<int>(); int currentNumber = inputList[0]; int occurrenceCount = 1; // Iterate through the sorted list starting from the second element for (int i = 1; i < inputList.Count; i++) { if (inputList[i] == currentNumber) { // Same number as before, increment count occurrenceCount++; } else { // We've hit a new number—check the count of the previous one if (occurrenceCount % 2 == 0) { // Add all occurrences of the even-count number to the result filteredList.AddRange(Enumerable.Repeat(currentNumber, occurrenceCount)); } // Reset tracking for the new number currentNumber = inputList[i]; occurrenceCount = 1; } } // Don't forget to check the last number in the list if (occurrenceCount % 2 == 0) { filteredList.AddRange(Enumerable.Repeat(currentNumber, occurrenceCount)); } return filteredList; }
Integrating This Into Your Program
To use this method, update your Main method and replace the call to CheckIfOddCount with this new method:
static void Main(string[] args) { Console.WriteLine("Enter a List of Random integers such that some of them appears Odd times"); List<int> myList = new List<int>(); ValidatingList(myList); // Use the optimized method instead of CheckIfOddCount myList = FilterEvenOccurrences(myList); int i = 0; do { Console.WriteLine(myList[i]); i++; } while (i != myList.Count); Console.ReadLine(); }
You can also remove the old CheckIfOddCount, OddNumberRemoveFromList, and IsOdd methods since they're no longer needed.
Why This Works Better
- Time Complexity: Sorting takes O(n log n) time, and the traversal is O(n)—this is a huge improvement over the original O(n²) approach, especially for larger lists.
- No Hash Tables: We're only using sorting and list operations, which aligns perfectly with your current focus on linear data structures.
- Safer: We create a new filtered list instead of modifying the original one while iterating, which avoids bugs from in-place list modifications.
内容的提问来源于stack exchange,提问作者Dinesh Kumar

