[Algorithm] Determine whether the array elements appear in pairs

You are given an array of integers. Your task is to create pairs of them such that each pair consists of equal numbers. Each array element can only belong to one pair. Is it possible to use all integers?
Write a function:
Function Solution(A)

If array A contains N integers, returns whether it is possible to split all integers into pairs.

  1. Given A = [1, 2, 2, 1], your function should return True because they are (A[0]). A[3]) (both have 1) and (A[1]). A[2]) (both have value 2)
  2. Given A=[7,7,7], your function should return False because you can generate a pair of numbers 7, but you still have a number 7
  3. If A=[1,2,2,3] your function should return False, because A does not have any value [0] to match

Write an efficient algorithm for the following assumptions:

Each element of array A is an integer in the range -1,0000010000].

Problem-solving ideas:

It is a bit similar to judging whether the parentheses appear in
pairs. 1. Create a stack for storing the array.
2. Loop the array to judge whether the current character exists in the stack.
3. If it exists, delete the element.
4. Finally, judge the element in the stack The number, if it is greater than 1, it means that the elements do not appear in pairs

function isDoubleStr(arr) {
	const n = arr.length;
	const stack = [], res = false
	if(len % 2 > 1) {
		return false
	}
	arr.forEach(item => { 
		let index = stack.indexOf(item) 
		if (index > -1) {
			stack.splice(index, 1)
		} else {
			stack.push(item)
		}
		
	})
	if(stack.length >= 1) {
		return false
	} else {
		return true
	}
}

Guess you like

Origin blog.csdn.net/weixin_38318244/article/details/124688259