簡體   English   中英

為什么跳出循環然后在循環后返回更快?

[英]Why is it faster to break out of a loop and then return after the loop?

目前,在解決 LeetCode 問題Two Sum之后,我正在快速旅行。

我的解決方案返回了3ms

public int[] twoSum(int[] nums, int target) {
            // define return array
            int[] result = {-1, -1};
            
            // define value, index
            Map<Integer, Integer> hashmap = new HashMap<>();
            
            // define begining ptr
            int lookingFor;
            
            // for loop
            for(int begPtr=0; begPtr<nums.length; begPtr++){
                // does the hashmap contain this integer
                lookingFor = target - nums[begPtr];
                    
                // check to see if element already exist
                if(hashmap.containsKey(lookingFor)){
                        result[0] = begPtr;
                        result[1] = hashmap.get(lookingFor);
                        return result;
                }
                    
                // add to hashmap    
                hashmap.put(nums[begPtr], begPtr);  
            }

            // return 
            return result;
    }

這是1ms方法(唯一的區別是if 語句中的中斷):

public int[] twoSum(int[] nums, int target) {
        int[] result = {-1, -1};
        Map<Integer, Integer> elements = new HashMap<>(); //number, index
        for(int i = 0; i < nums.length; i++) {
            int element = nums[i];
            int complement = target-element;
            if (elements.containsKey(complement)) {
                result[0] = i;
                result[1] = elements.get(complement);
                break;
            }
            elements.put(element, i);
        }
        return result;
    }

為什么跳出循環然后在循環后返回更快?

一般來說,您不必擔心使用returnbreak 這絕對不是LeetCode任務的重點。 您的解決方案的另一個方面存在問題。

要回答為什么一個解決方案快1ms的問題,你應該知道LeetCode引擎的測試實例設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM