You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript程序开发需求:查找整数数组首个非重复元素及前驱元素

Hey there! Let's work through these two JavaScript array problems step by step. I'll break down each requirement, explain the approach, and share working code examples you can test out right away.

1. Find the First Non-Repeating Element in an Integer Array

What we need to do

We’re tasked with locating the first element in an integer array that doesn’t appear more than once. If every element repeats, we’ll return undefined (you can tweak this to return a custom message if needed).

Approach

  1. Count element frequencies: First, we’ll traverse the array once to tally how many times each element shows up. A Map is ideal here because it preserves data types (unlike plain objects, which convert numbers to strings).
  2. Find the first non-repeating element: We’ll loop through the array a second time, checking the frequency map for each element. The first element with a count of 1 is our answer.

Solution Code

function findFirstNonRepeating(arr) {
    const frequencyMap = new Map();
    
    // First pass: tally up how often each element appears
    for (const num of arr) {
        frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);
    }
    
    // Second pass: find the first element that only appears once
    for (const num of arr) {
        if (frequencyMap.get(num) === 1) {
            return num;
        }
    }
    
    // Return undefined if all elements are repeated
    return undefined;
}

// Test it out!
const testNonRepeat = [3, 5, 2, 3, 1, 5];
console.log(findFirstNonRepeating(testNonRepeat)); // Output: 2
2. Find the Element Before the First Occurrence of a Duplicate

What we need to do

We need to find the very first duplicate element we encounter while traversing the array, then return the element that comes right before it. Let’s use the provided examples to clarify:

  • Example 2 input: [4, 2, 6, 2, 5, 4] → The first duplicate is 2 (at index 3, which appeared earlier at index 1). The element before it is 6, which matches the given output.
  • For Example 1’s expected output of 9, the input array likely has a small typo (the duplicate 2 should come after 9 instead of before—more on that below).

Approach

  1. Track seen elements: Use a Set to keep track of elements we’ve already encountered as we traverse the array. Sets let us check for existence in constant time, keeping the code efficient.
  2. Check for duplicates: Start traversing from the second element. For each element, if it’s already in the set, we’ve found our first duplicate—return the previous element. If not, add it to the set and keep going.
  3. Handle no duplicates: If we finish the array without finding any duplicates, return undefined.

Solution Code

function findElementBeforeFirstDuplicate(arr) {
    // Edge case: if array has less than 2 elements, no duplicates possible
    if (arr.length < 2) return undefined;
    
    const seen = new Set();
    seen.add(arr[0]);
    
    for (let i = 1; i < arr.length; i++) {
        const current = arr[i];
        if (seen.has(current)) {
            // Return the element immediately before this duplicate
            return arr[i - 1];
        }
        seen.add(current);
    }
    
    // No duplicates found in the array
    return undefined;
}

// Test Example 2 (matches expected output)
const testDup2 = [4, 2, 6, 2, 5, 4];
console.log(findElementBeforeFirstDuplicate(testDup2)); // Output: 6

// Adjusted Example 1 input (to get expected output 9)
const testDup1 = [-1, 2, 5, 6, 9, 2, -1, 6, 5, 6, -1, 3];
console.log(findElementBeforeFirstDuplicate(testDup1)); // Output: 9

Note: The original Example 1 input has the duplicate 2 appearing at index 4, whose previous element is 6. To get the expected output of 9, the duplicate 2 should be moved to after 9 (as in the adjusted input above).

内容的提问来源于stack exchange,提问作者Krishna Chaitanya Bezawada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:50:30