如何计算数组中有多少对数字

时间:2019-10-02 18:49:02

标签: javascript arrays node.js

我目前正在执行此作业,这困扰着我如何计算数组中多少对数字

这是我以前尝试过的

Connection conn;

        try {
//          com.microsoft.sqlserver.jdbc.sqlserver.SQLServerDriver
            Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();

            // jdbc and jtds are the drivers that allow the connection to outside databases
            // sq41ddb.na.steelcase.net:3250 is the server and port that are need to connect to the scrapMinder database
            String connString = "jdbc:jtds:sqlserver://SQLSERVER;databaseName=DATABASENAME;user=USERNAME;password=PASSWORD";

            conn = DriverManager.getConnection(connString);

            Log.i("Connection", "Open");
            Log.i("SEND TO DB", "Date: " + date + " Time: " +time);
            Statement statement = conn.createStatement();

            statement.executeUpdate("Insert Into DATABASENAME (Date, Time) \n" +
                    "values ('" + date + "', '" + time +"' );"); //SQL SELECT STATEMENT TO INSERT INTO DATABASE 
            statement.setQueryTimeout(0);


        } catch (Exception e) {
            Log.e("Error SendToDB", e.toString());
        }

但不幸的是,回报总是

 function pairNumber (n,ar)
  let numberOfPairs=0
    for(let i =0;i<ar.length;i++){
        for(let j =1;j<ar.length;j++){
            if (ar[i] == ar[j]){
                          console.log([ar[i], ar[j]], '<< ini isinya')
                          console.log(ar[i+1], ar[j+1])

                numberOfPairs++
                ar.splice(i,1)
                ar.splice(j,1)
            }
        }
    }

    if(n%3 == 0){
      numberOfPairs -= 1
      return numberOfPairs
    } else {
      return numberOfPairs
    }
}

console.log(sockMerchant(9,[10,20,20,10,10,30,50,10,20]))
console.log(sockMerchant(10,[1,1,3,1,2,1,3,3,3,3]))

正确答案应该是

4
4

对于这两种情况,有人可以帮我我所缺少的吗?谢谢你!

3 个答案:

答案 0 :(得分:1)

我只是先对数组进行排序,然后只需要循环数组1次即可。最好控制您的代码

function pairNumber (n,ar){
        let numberOfPairs=0
        let i = 0
        let j = 1

        ar.sort()
         for(let i = 0; i < ar.length; i++){
             if(ar[i] == ar[i++]){
                 numberOfPairs++
                 i+=1
             }
         }
         return numberOfPairs
     }

答案 1 :(得分:0)

由于这是一个简单的任务,因此我将不作详细解释。问题似乎出在循环变量初始化中。 提示:j=i+1

答案 2 :(得分:0)

要克服O(n 2 )的二次方方法,可以带一个对象并计数发生次数。

最后,通过仅计算下限的一半值来返回总和。

function pairNumber(n, array) {
    var numberOfPairs = 0,
        counts = {};
  
    for (let v of array) {
        if (!counts[v]) counts[v] = 0;
        ++counts[v];
    }

    for (let count of Object.values(counts)) numberOfPairs += count >> 1;

    return numberOfPairs;
}

console.log(pairNumber(9, [10, 20, 20, 10, 10, 30, 50, 10, 20]))
console.log(pairNumber(10, [1, 1, 3, 1, 2, 1, 3, 3, 3, 3]))