试图解释这个Java代码片段

时间:2012-01-27 16:17:58

标签: java c

道歉,如果这似乎与我编写的代码无关,但是想要了解这些Java代码片段中发生了什么(我不理解Java,我可以解码它)。我想在C中实现这些片段(我知道这一点)。我在片段中看到有一些Hash Table搜索正在进行,就像一个数组的元素用作搜索其他数组的键,但无法正确获取它。

1] Snippet 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] Snippet 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 个答案:

答案 0 :(得分: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]在此实现中有效。

答案 1 :(得分:1)

我赞成了@The Baumann的解决方案,但我建议有一个更简单的解决方案。 java.util.HashSet.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;
}
相关问题