找到数组的第一个非重复整数

时间:2018-03-25 15:43:25

标签: java arrays algorithm nested-loops

这个程序为所有非重复元素提供输出,但我首先需要一个非重复元素。在j循环结束后,我试图让if(flag==1)断开循环,然后我测试但它并不适用于所有情况

import java.util.Scanner;
public class first
{
    public static void main(String[] args) 
    {
        int n, flag = 0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter no. of elements you want in array:");
        n = s.nextInt();
        int a[] = new int[n];
        System.out.println("Enter all the elements:");
        for(int i = 0; i < n; i++)
        {
            a[i] = s.nextInt();
        }
        System.out.print("Non repeated first element is :");
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(i != j)
                {
                    if(a[i]!= a[j])
                    {
                        flag = 1;

                    }
                    else
                    {
                        flag = 0;
                        break;
                    }
                    if(flag == 1)
                    {
                     System.out.print(" ");   
                     System.out.println(a[i]);
                     break; 
                    }
                }
            }

        }

    }
}

10 个答案:

答案 0 :(得分:0)

You can construct two sets, singleSet and repeatedSet, respectively for elements appeared once and more than once. They can be created by doing one iteration on elements. Then, you do an a second iteration, to query which is the first element non-repeated:

int[] elements = { 1, 1, 2, 3, 3, 4 };
Set<Integer> singleSet = new HashSet<>();
Set<Integer> repeatedSet = new HashSet<>();

for (int e : elements) {
    if (repeatedSet.contains(e)) {
        continue;
    }
    if (singleSet.contains(e)) {
        singleSet.remove(e);
        repeatedSet.add(e);
    } else {
        singleSet.add(e);
    }
}

for (int e : elements) {
    if (singleSet.contains(e)) {
        return e;
    }
}

This solution is a O(n) solution, it should be faster than the nested-loop, which is O(n^2).


You can also replace the singeSet by a singleList, and at the end, return the first element in the singleList, which avoid the 2nd iteration on elements. Thus the solution is even faster.

答案 1 :(得分:0)

根据@Mincong中的两个集合的概念,我在这里添加他提到的更快的解决方案。

int[] array = { 1, 1, 2, 3, 3, 4 };

Set<Integer> allValues = new HashSet<>(array.length);
Set<Integer> uniqueValues = new LinkedHashSet<>(array.length);

for (int value : array) {
    if (allValues.add(value)) {
        uniqueValues.add(value);
    }
    else {
        uniqueValues.remove(value);
    }
}

if (!uniqueValues.isEmpty()) {
    return uniqueValues.iterator().next();
}

答案 2 :(得分:0)

Python数组中的第一个非重复整数

def non_repeating(arr):
    non_repeating = []
    for n in arr:
        if n in non_repeating:
            non_repeating.pop(non_repeating.index(n))
        else:
            non_repeating.append(n)

    return non_repeating[0] if non_repeating else None


print(non_repeating([1, 1, 1, 5, 2, 1, 3, 4, 2]))

答案 3 :(得分:0)

def solution(self, list):
    count_map = {}

    for item in list:
        if item in count_map:
            count_map[item] += 1
        else:
            count_map.setdefault(item, 1)

    for item in list:
        if count_map[item] ==1:
            return item
    return None

答案 4 :(得分:0)

这是一个试图实现相同功能的python代码-

def singleNumber(nums: List[int]) -> int:
        from collections import defaultdict
        memory = defaultdict(int)
        for num in nums:
            memory[num] += 1
        for k,v in memory.items():
            if v == 1:
                return k

答案 5 :(得分:0)

JavaScript

function nonRepeatinInteger(arr) {
    let val = [], count = [];
    arr.forEach((item, pos) => {
        if (!val.includes(item)) {
            val.push(item);
            count[val.indexOf(item)] = 1;
        } else {
            count[val.indexOf(item)]++;
        }
    });
    return val[count.indexOf(Math.min(...count))];
}
console.log(nonRepeat([-1, 2, -1, 3, 2]));
console.log(nonRepeat([9, 4, 9, 6, 7, 4]));

答案 6 :(得分:0)

 private int getFirstNonRepeating(int[] arr) {
    Set<Integer> set = new HashSet<>();
    ArrayList<Integer> list = new ArrayList<>();
    int min = 0;
    for (int i = 0; i <arr.length; i++) {
        //Parsing though array and adding to list if set.add returns false it means value is already available in set
        if (!set.add(arr[i])) {
            list.add(arr[i]);
        }
    }
    //Parsing though array and checking if each element is not available in set,then that is smallest number
    for (int i = 0; i < arr.length; i++) {
        if (!list.contains(arr[i])) {
            min = arr[i];
            break;
        }
    }
    Log.e(TAG, "firstNonRepeating: called===" + min);
    return min;
}

答案 7 :(得分:0)

尝试一下:

int a[] = {1,2,3,4,5,1,2};
        
        for(int i=0; i<a.length;i++) {
            int count = 0;
            for(int j=0; j<a.length;j++) {
                if(a[i]==a[j] && i!=j) {
                    count++;
                    break;
                }
            }
                if(count == 0) {
                    System.out.println(a[i]);
                    break;              //To display first non repeating element
                }
        }

答案 8 :(得分:0)

使用 JS 对象:

function nonRepeat_Using_Object(arr) {
    const data = arr.reduce((acc, val) => {
        if (!acc[val]) {
            acc[val] = 0;
        }
        acc[val]++;
        return acc;
    }, {});
    for (let i = 0; i < arr.length; i++) {
        if (data[arr[i]] === 1) {
            return arr[i];
        }
    }
}

答案 9 :(得分:-1)

另一种实现方法:您可以使用哈希图在第一遍中存储整数的计数,并在第二遍中返回计数为1的第一个元素。

相关问题