[英]Find the first non repeating integers of array
該程序為所有非重復元素提供輸出,但我首先需要一個非重復元素。 我試圖保持if(flag==1)
在 j 循環結束后中斷循環,然后我進行了測試,但它不適用於所有情況
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;
}
}
}
}
}
}
您可以分別為出現一次和repeatedSet
的元素構造兩個集合, singleSet
和repeatedSet
集。 它們可以通過對元素進行一次迭代來創建。 然后,您進行第二次迭代,以查詢哪個是非重復的第一個元素:
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;
}
}
這個解決方案是一個O(n)
解決方案,它應該比嵌套循環更快,它是O(n^2)
。
您還可以將singeSet
替換為singleList
,最后返回singleList
的第一個元素,從而避免對元素進行第二次迭代。 因此,解決方案甚至更快。
跟進@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();
}
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]))
def solution(self, list):
count_map = {}
for item in list:
count_map[item] = count_map.get(item, 0) + 1
for item in list:
if count_map[item] == 1:
return item
return None
這是一個試圖實現相同目標的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
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]));
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;
}
試試這個:
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
}
}
使用 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];
}
}
}
實現此目的的另一種方法:您可以使用哈希圖在第一次傳遞中存儲整數計數,並在第二次傳遞中返回計數為 1 的第一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.