简体   繁体   English

如何在没有循环的情况下扫描和比较数组中的值

[英]How to scan in and compare values in an array without loops

I have an assignment to do where I need to scan a number of cases. 我有一项任务需要做一些案件的扫描。 In each case, you're given an array and a target. 在每种情况下,都为您提供一个数组和一个目标。 The goal is to scan the array to find a set of two numbers which add up to the target. 目的是扫描阵列以找到两个数字的集合,这些数字加起来等于目标。

My issue is I need to get my big-oh (the run time) to equal n, which means I can have at most a single loop. 我的问题是我需要使big-oh(运行时间)等于n,这意味着我最多只能有一个循环。 This is my code as it stands now. 这是我现在的代码。

//Assume that cases, sizeofarray, array, and target already exist.    
while(cases =! 0){
        scanf("%d", @sizeofarray);
        scanf("%d", @target);

        array = malloc(sizeof(int) * sizeofarray);
    }

As you can see the requirement to function for multiple cases already removes my ability to use additional loops within the function. 如您所见,对多种情况起作用的要求已经消除了我在函数内使用其他循环的能力。 Therefor I need to both scan in and compare values in the array without using a for loop. 因此,我需要在不使用for循环的情况下扫描并比较数组中的值。

I suppose the other option is to not loop with the case value, thereby enabling me to use a loop elsewhere and keeping my big-oh run time below n. 我想另一种选择是不使用case值循环,从而使我能够在其他地方使用循环,并使big-oh运行时间保持在n以下。

If anybody can help me, I would appreciate it. 如果有人可以帮助我,我将不胜感激。 To reiterate, I need to know if there exists a technique to scan in values into an array without looping, for comparing values in an array without looping, or for scanning multiple cases without looping. 重申一下,我需要知道是否存在一种无需循环就可以将值扫描到数组中的技术,无需循环就可以比较数组中的值,或者无需循环就可以扫描多种情况。

This is a classic two sum problem. 这是一个经典的两和问题。 Use HashMap to store the target value. 使用HashMap存储目标值。 I am providing a Java sample for your reference. 我正在提供一个Java示例供您参考。 I think it can be easily converted to C++ code 我认为可以轻松将其转换为C ++代码

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    int[] result = new int[2];

    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(numbers[i])) {
            int index = map.get(numbers[i]);
            result[0] = index+1 ;
            result[1] = i+1;
            break;
        } else {
            map.put(target - numbers[i], i);
        }
    }

    return result;
    }
}

Time complexity depends on the put and get operations of HashMap which is normally O(1). 时间复杂度取决于HashMap的放置和获取操作,通常为O(1)。

Time complexity of this solution is O(n). 该解决方案的时间复杂度为O(n)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM