Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何改进返回未配对元素的代码_Java_Performance - Fatal编程技术网

Java 如何改进返回未配对元素的代码

Java 如何改进返回未配对元素的代码,java,performance,Java,Performance,我正在为即将到来的编码面试进行练习,下面是我的一个练习问题,以及我已经走了多远 我如何改进该计划,你有什么建议 还有,是否有任何城市可以帮助我提高编码技能 问题, A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with a

我正在为即将到来的编码面试进行练习,下面是我的一个练习问题,以及我已经走了多远

我如何改进该计划,你有什么建议

还有,是否有任何城市可以帮助我提高编码技能

问题,

    A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

    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.
    Write a function:

    class Solution { public int solution(int[] A); }
给定一个由满足上述条件的N个整数组成的数组A,返回未配对元素的值

    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
    the function should return 7, as explained in the example above.

    Assume that:

    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.
    Complexity:

    expected worst-case time complexity is O(N);
    expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
    Elements of input arrays can be modified.


Solution;

import java.util.*;

public class Solution {
    public int solution(int[] A) {
            int x;

        for(int i = 0; i < 7; i++)
        {
             //create an integer array containing an odd number of elements of numbers ranging from 1 - 1,000,000

//for(int N = 1; N <= 1,000,000; N++)

            int N = 1;

            while(N > 1 && N <= 1000000)
            {

                //check if N is odd then assign to the array               

                if(N != N/2)
                {
                    A[i] = N;
                }
            }

            //check for any element not paired more than once

            if(A[i] != A[i++])
            {
                x = A[i];
            }
            else 
                return 0;
        }

        //return unpaired elemnent
        return x;
    }
}
例如,给定一个数组:
A[0]=9A[1]=3A[2]=9
A[3]=3A[4]=9A[5]=7
A[6]=9
该函数应返回7,如上面示例中所述。
假设:
N是范围[1..1000000]内的奇数整数;
数组A的每个元素都是[1..100000000]范围内的整数;
除一个值外,所有值都会出现偶数次。
复杂性:
期望最坏情况时间复杂度为O(N);
预计最坏情况下的空间复杂度为O(1),超出输入存储空间(不计算输入参数所需的存储空间)。
可以修改输入数组的元素。
解决方案
导入java.util.*;
公共类解决方案{
公共int解决方案(int[]A){
int x;
对于(int i=0;i<7;i++)
{
//创建一个整数数组,其中包含奇数个从1到1000000的数字元素

//对于(intn=1;n1&&N这样的东西应该可以工作,在这里,我以一种方式实现了它,在这种方式中,我测试了它得到的所有int,并仅在有解决方案时返回(注意,必须有一个默认值,可能是处理“无解决方案”的更好方式)

公共类解决方案{
公共int解决方案(int[]A){
boolean-possibleSolution=true;//返回并在不可能时正确断开
for(int i=0;i
请注意,此处不包括添加int,因为不确定需要什么类型的值


但只需添加它们,然后传递数组,如果可能有多个答案,则不返回add to a
List results=new ArrayList();
,在运行完所有
i
之后,返回
结果
,此时
返回0;

接受的解决方案违反了要求:

预期最坏情况时间复杂度为O(N)

因为它具有二次复杂性(两个嵌套循环)。一个明显的快速解决方案是使用
哈希集
来记住尚未配对的数字。但这会违反其他要求:

预期最坏情况下的空间复杂度为O(1)

有一个简单的技巧可以同时满足这两个要求:

public int solution(int[] A) {
    int result = 0;
    for (int x : A) result ^= x;
    return result;
}
这使用了一个事实,
x^x==0
对于任何
x
^
的关联性。这意味着任何一对相等的值都会抵消,剩下的是单个未配对的值(在多个未配对的值的情况下,结果没有意义;这种情况无法检测)



Mikenno接受的解决方案是错误的。对于输入的
{1,1,1}
有一对1和一对未配对的1,因此结果应该是
1
,但它返回
0

这个答案是在可编码性上测试的,它的性能和正确性得到100%

我正在做的是:

  • 对数组进行排序,使对聚集在一起,因此我将能够通过迭代来检查数组中的每两对

  • 然后我在两个索引中添加2以获得下一对,以此类推

  • 第一个不匹配意味着我们已经找到了目标,因为两个索引都指向pairs

  • 代码如下:

    public static int solution (int[] x) {
        int found = 0;
        int i = 0;
        int j = 1;
    
        Arrays.sort(x);
        //To sort the array so if you have {9 , 3 , 9 , 3 , 9 , 7 , 9} 
        //it will be { 3 , 3 , 7 , 9 , 9 , 9 , 9}
        if (x.length == 1) {
            found = x[0];
        }
    
        while (x.length % 2 == 1 && i < x.length && j < x.length) {
            if (x[i] == x[i+1]) {
                i = i + 2;
                j = j + 2;  
            } else {
                found = x[i];
                break;
            }
        }
    
        if (found == 0 && i == x.length-1) {
            found = x[i];
        }
    
        return found;
    }
    
    公共静态int解决方案(int[]x){
    int=0;
    int i=0;
    int j=1;
    数组。排序(x);
    //对数组进行排序,如果有{9,3,9,3,9,7,9}
    //它将是{3,3,7,9,9,9,9}
    如果(x.length==1){
    发现=x[0];
    }
    而(x.length%2==1&&i
    嗨,我找到了这个答案

    import java.util.*;
    
    class Solution {
    public int solution(int[] A) {
    
        Arrays.sort(A);
    
        int ctr = 1, result = 0;
    
        for (int x = 0; x < A.length - 3; x+= 2){
    
            if(A[x] != A[ctr] && A[ctr] == A[ctr+1] ){
                return A[x];
            }
            ctr +=2;
         }
    
        return A[A.length-1];
    }
    
    }
    
    import java.util.*;
    类解决方案{
    公共int解决方案(int[]A){
    数组。排序(A);
    int ctr=1,结果=0;
    对于(int x=0;x
    我知道这不是java,而是PHP,但登录可以应用于任何地方,我在这里没有看到这种解决方案:

    function solution($A) {
    
     sort($A); //sort the array
     $arrString = implode("-",$A); // make the string
    
     foreach($A as $a):
        $str = (string)$a . '-' . (string)$a; // generate the string we will search
        if (strpos($arrString, $str) === false) return $a; //if the string dont exist return the number
     endforeach;
    }
    
    我的尝试:)

    public int解决方案(int[]arr){
    如果(arr.length==1)返回arr[0];
    数组。排序(arr);
    int奇数=-1;
    对于(int i=0;ifunction solution($A) {
    
     sort($A); //sort the array
     $arrString = implode("-",$A); // make the string
    
     foreach($A as $a):
        $str = (string)$a . '-' . (string)$a; // generate the string we will search
        if (strpos($arrString, $str) === false) return $a; //if the string dont exist return the number
     endforeach;
    }
    
    public int solution(int[] arr) {
    
        if (arr.length == 1) return arr[0];
        Arrays.sort(arr);
    
        int odd = -1;
    
        for (int i = 0; i < arr.length; i++) {
    
            if (i == arr.length-1) {
                odd = arr[i];
                break;
            }
            if (arr[i] == arr[i + 1]) {
    
                i++;
                continue;
            }
    
            odd = arr[i];
        }
    
       return odd; 
    }
    
    public int solution(int[] A) {
        // write your code in Java SE 8
        if (A.length == 0){
            return 0;
        }
        if (A.length == 1) {
            return A[0];
        }
        Arrays.parallelSort(A);
        for(int i=0; i<A.length-2; i+=2) {
            if(A[i]!=A[i+1])
                return A[i];
        }
        return A[A.length-1];
    }
    
    let arr:[Int] = [1, 2, 3, 2, 4, 5, 4, 1, 3]
    
    var valuesDict:[Int:Int] = [:]
    
    for num in arr {
        if let value = valuesDict[num] {
            valuesDict[num]! += 1
        } else {
            valuesDict[num] = 1
        }
    }
    
    print(valuesDict)
    
    var unpairedElement:Int?
    for (key, value) in valuesDict {
        if value == 1 {
            unpairedElement = key
            break
        }
    }
    
    print("unpaired element is \(unpairedElement!)")
    
    def solution(a)
      hash = {}
      a.each do |n|
        if hash[n]
          hash.delete(n)
        else
          hash[n] = 1
        end
      end
      hash.keys.first
    end
    
     public int solution(int[] A) {
    
        if (A.length == 0){
            return 0;
        }
    
        if (A.length == 1) {
            return A[0];
        }
    
        Hashtable<Integer, Integer> occurrences = new Hashtable<Integer, Integer>();
    
        for(int i=0; i< A.length; i++)
        {
            if (occurrences.containsKey(A[i]))
            {
                occurrences.remove(A[i]);
            }
            else
            {
                occurrences.put(A[i], 1);    
            }
        }
    
        // find unpaired element
        for(Map.Entry<Integer, Integer> entry: occurrences.entrySet())
        {
            if(entry.getValue() == 1)
            {
                return entry.getKey();
            }
        }
    
        return 0;
    }
    
    import Foundation
    import Glibc
    
    // you can write to stdout for debugging purposes, e.g.
    // print("this is a debug message")
    
    public func solution(_ A : inout [Int]) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    
    var dict = Dictionary<Int, Int>()
    
    if A.count == 1 { return A[0] }
    
    for i in 0..<A.count {
    
        if dict.keys.contains(A[i]) {
            dict[A[i]] = nil    
        }
        else {
            dict[A[i]] = 1
        }
    }
    
    for (k,v) in dict 
    {
        if v == 1 {
            return k
        }
    }
    
    return 0;
    }
    
    public func solution(_ A : inout [Int]) -> Int? {
    
    let sorted = A.sorted()
    var hashmap = [String: Int]()
    
    for value in sorted {
    
        let key = String(describing: value)
        if (hashmap[key] != nil) {
    
            hashmap[key]! += 1
        } else  {
    
            hashmap[key] = 1
        }
    }
    
        for (key, value) in hashmap {
    
            if value == 1 {
                return Int(key) ?? 0
            }
        }
    return nil
    }
    
    def solution(a)
    
      summ = 0
      rrr = 1
    
      a.sort.each do |el|
    
        summ = summ + el * rrr
        rrr = -rrr
    
      end
      summ
    
    end
    
    public int solution(int[] A) {
          HashMap<Integer, Integer> hashMap = new HashMap<>();
          for(Integer a : A) {
             if(hashMap.containsKey(a)) {
                hashMap.put(a, hashMap.get(a)+1);
             } else {
                hashMap.put(a, 1);
             }
          }
          for(Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
             if(entry.getValue() % 2 == 1) {
                return entry.getKey();
             }
          }
          return 0;
    }
    
    function solution(A) {
      let mapObject={}
      for(let i=0;i<A.length;i++){
         if(mapObject[A[i]])
         {
           delete mapObject[A[i]]
         }else{
           mapObject[A[i]]=A[i];
         }
       }
     return Object.values(mapObject)[0];
    
    def solution(A):
    # write your code in Python 3.6
    odd = -1
    if len(A) == 1:
        return A[0]
    A.sort()
    i = 0
    while i<len(A):
        if i == len(A) - 1:
            odd = A[i]
            break
        
        if A[i] == A[i+1]:
            i+=2
            continue
            
        odd = A[i]
        i+=1
    
    return odd
    
    public int solutionOk(int[] A) {
        Set<Integer> set = new HashSet<>();
        for (int a : A) {
            if (!set.remove(a)) {
                set.add(a);
            }
        }
        return set.stream().iterator().next();
    }
    
    public int solution(int[] A) {
        return Arrays.stream(A).reduce(0, (a, b) -> a ^ b);
    }
    
    def solution(A):
        A=sorted(A)
        return abs(sum(A[::2])-sum(A[1::2]))