查找不构成列表中的对的奇数整数

时间:2018-10-19 03:58:48

标签: python arrays list

我有一个要解决的问题!

给出了一个由N个整数组成的非空数组A。该数组包含奇数个元素,并且该数组的每个元素都可以与另一个具有相同值的元素配对,除了一个未配对的元素。

For example, in array A such that:   A[0] = 9  A[1] = 3  A[2] = 9   A[3] = 3  A[4] = 9  A[5] = 7   A[6] = 9

    the elements at indexes 0 and 2 have value 9,
    the elements at indexes 1 and 3 have value 3,
    the elements at indexes 4 and 6 have value 9,
    the element at index 5 has value 7 and is unpaired.

编写函数:

def solution(A)

给定一个数组N,该数组A由满足上述条件的N个整数组成,则返回未配对元素的值。

For example, given array A such that:
  A[0] = 9  A[1] = 3  A[2] = 9
  A[3] = 3  A[4] = 9  A[5] = 7
  A[6] = 9

该函数应返回7,如上面的示例所述。

为以下假设写出有效的算法:

    N is an odd integer within the range [1..1,000,000];
    each element of array A is an integer within the range [1..1,000,000,000];
    all but one of the values in A occur an even number of times.

我认为我只是解决问题的一半:

def findOddItem(A):
    for i, item in enumerate(A): # look to left not immidiate one
        if A[i] != A[i - 2]:
            print A[i]

但是这看起来像打印了错误的结果。

4 个答案:

答案 0 :(得分:1)

我会与reduce()结合使用functools.reduce()(在Python 3.x中已移至operator.xor()):

# Uncomment for Python 3.x:
# from functools import reduce
import operator

def solution(A):
    return reduce(operator.xor, A)

arr = [9, 3, 9, 3, 9, 7, 9]

print(solution(arr))  # 7

这是一种O(n)解决方案,非常干净。

答案 1 :(得分:0)

您可以使用“或”按位运算符。由于除一个元素外,所有元素都发生两次,所以它们会互相抵消,而只发生一次。

import java.util.Scanner;

public class Task2 {
    public static void main(String[] args) {
        Task2 task2 = new Task2();

//        Scanner sc = new Scanner(System.in);
//        int a = sc.nextInt();
//
//        task2.solution(a);

        task2.test(123, 6);
        task2.test(Integer.MAX_VALUE, 46);
    }

    private int solution(int number) {
        // get remainder
        int remainder = number % 10;
        // exclude remainder
        int div = number / 10;

        // recursively find sum of remainders until div would be zero
        if (div == 0 ) {
            return remainder;
        }
        return remainder + solution(div);
    }

    private void test(int a, int expected) {

        long start = System.nanoTime();
        System.err.print("Test isSuccess: " + assertTrue(expected, solution(a)));
        long total = System.nanoTime() - start;
        System.err.println(", run time: " + (total / 1000.0/ 1000));
    }

    // testing
    private boolean assertTrue(int expected, int actual) {
        return expected == actual;
    }
  }

时间复杂度O(n)空间复杂度O(1)。 希望这会有所帮助。

答案 2 :(得分:0)

由于没有条件,只有一个元素发生两次两次,我想这也可能意味着4、6,...次。

在这种情况下,我宁愿使用numpy.bincount来查看哪个整数具有奇数。

a = [1,1,2,2,3,3,5,3,3,4,5,5,5,10,10]
a_cnt = list(numpy.bincount(a))
for i in a_cnt:
    if i != 0 and i%2 == 1:
        print(a_cnt.index(i))
# 4

答案 3 :(得分:0)

您可以使用“ xor”按位运算符。由于除一个元素外,所有元素都发生两次,所以它们会互相抵消,而只发生一次。

def SingleOccurance( arr, n): 

result = arr[0] 

# Do XOR of all elements and return as 'a' xor 'a' is 0 and except single 
# occured number rest will turn to 0 and 'a' xor 0 is 'a'
for i in range(1,n): 
    result = res ^ arr[i] 

return result

我们可以对所有数字的相同位置的位求和,并对3取模。总和不是3的倍数的位是一次出现的数字位。

让我们考虑示例数组{5,5,5,8}。 101、101、101、1000

首位总和%3 =(1 +1 +1 + 0)%3 = 0

秒数之和%3 =(0 + 0 + 0 + 0)%0 = 0

第三位的总和%3 =(1 +1 +1 + 0)%3 = 0

第四位的总和%3 =(1)%3 = 1 因此,一次出现的数字是1000

代码:

INT_SIZE = 32

def getSingle(arr, n) : 

    # Initialize result 
    result = 0

    # Iterate through every bit 
    for i in range(0, INT_SIZE) : 

        # Find sum of set bits  at ith position in all array elements 
        sm = 0
        x = (1 << i) 
        for j in range(0, n) : 
            if (arr[j] & x) : 
                sm = sm + 1

        # The bits with sum not multiple of 3, are the 
        # bits of element with single occurrence. 
        if (sm % 3) : 
            result = result | x 

    return result