有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

c试图得到这个Java代码片段的解释

如果这似乎与我所写的代码无关,但我想了解这些Java代码片段中发生了什么(我对Java的理解还不够透彻,无法对其进行解码),我深表歉意。我想用C语言实现这些代码片段(我对C语言相当了解)。我在代码片段1中看到一些哈希表搜索正在进行,就像一个数组的元素用作键来搜索另一个数组一样,但无法正确获取它

1]片段1

它试图解决的问题是:找到数组的第一个覆盖前缀

例如,以下5的第一个覆盖前缀−元素数组A:

A[0] = 2  A[1] = 2  A[2] = 1
A[3] = 0  A[4] = 1

是3,因为序列[A[0],A[1],A[2],A[3]]等于[2,2,1,0],包含数组A中出现的所有值

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;


class FirstCovering {
    int ps ( int[] A ) {
        ArrayList<Integer> arrA = new ArrayList<Integer>(A.length);
        for (int i = 0; i < A.length; i++) {
                arrA.add(A[i]);
        }

        HashSet<Integer> hashSet = new HashSet<Integer>(arrA);
        Iterator<Integer> iter = hashSet.iterator();

        int index = 0, tempIndx=0;
        while (iter.hasNext()) {

                tempIndx = arrA.indexOf(iter.next());
                if (tempIndx > index ) index = tempIndx;
        }

        return index;
    }
}

2]片段2

class ComplementaryPairs {

  private static String palindrome;
  public static void main(String[] args) {

    int array[] = {4,5};
    int a = complementary_pairs(6, array);
    System.out.println(a);

    int array2[] = {4,5};
    int b = complementary_pairs(4, array2);
    System.out.println("b = " + b);
   }

  static int complementary_pairs ( int k,int[] A ) {
    // find count of complementary pairs from array A.
    int count = 0;
    for (int i = 0; i < A.length; i++) {
      for (int j = 0; j < A.length; j++) {
        if (A[j] + A[i] == k) {
          count++;
        }
      }
    }
    return count;
  }
}

共 (2) 个答案

  1. # 1 楼答案

    关于代码片段1,您是正确的,尽管您可以在数组的一次传递中完成此操作

    public int lastNonRepeat( int[] a )
    {
        HashMap map = new HashMap();
        int lastIndex = 0;
        for( int i = 0; i < a.length; i++ )
        {
            if( !map.containsKey(a[i]) )
            {
                map.put(a[i],true);
                lastIndex = i;
            }
        }
        return lastIndex;
    }
    

    对于代码片段2,互补对部分只是检查数组中两个数字的和是否等于k。该方法的时间复杂度为O(n^2)

    注意:a[0]+a[0]在此实现中有效

  2. # 2 楼答案

    我高估了真正的鲍曼解决方案,但我认为还有一个更简单的解决方案。爪哇。util。哈希集。add()函数仅在add修改集合时返回true,因此可以执行以下操作:

    public int ps( int[] a ) {
        HashSet set = new HashSet();
        int lastIndex = 0;
        for( int i = 0; i < a.length; i++ ) {
            if( set.add(a[i]) ) {
                lastIndex = i;
            }
        }
        return lastIndex;
    }