اذهب إلى المحتوى
  • 0

سبب رفض حل المسألة على leetcode

Ail Ahmed

السؤال

السلام عليكم

ده مسائل من LeetCode 

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

وده الحل بتاعي 

# Interview Google 
class Solution:
    def towSum(self,nums,target):
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    print(f"{nums[i]} + {nums[j]} = {target}")
                    return 1
        print("Not Found")
        return 0

num = Solution()
num.towSum([2,7,11,15],9) 

الكود ده بيشتغل عادي علي Vscode ولكن علي LeetCode مش بيشتغل وبيظهار الخظاء ده

SyntaxError: invalid syntax
                                            ^
    print(f"{nums[i]} + {nums[j]} = {target}")
Line 7  (Solution.py)

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

منصة leetcode تستخدم إصدار أقدم من بايثون ولا يدعم سلسلة f والتي تم تقديمها في الإصدار 3.6.

أيضًا أنت تقوم بإرجاع 1 أو 0 بدلاً من مصفوفة تحتوي على مؤشرات العناصر التي مجموعها يساوي الهدف، كما هو مطلوب في LeetCode. 

وللعلم استخدام nested loops أي حلقتين متداخلتين يؤدي إلى تعقيد زمني من الدرجة O(n^2)، حيث n هو عدد العناصر في المصفوفة، بمعنى وقت التنفيذ يزداد بشكل سريع جدًا مع زيادة حجم المصفوفة.

لذا اعتمد على ميثود format وتعديل الكود كالتالي:

class Solution:
    def twoSum(self, nums, target):
        num_map = {}  

        for i, num in enumerate(nums):
            complement = target - num  
            
            if complement in num_map:
                return [num_map[complement], i] 
              
            num_map[num] = i  
        return []  

num = Solution()
result = num.twoSum([2, 7, 11, 15], 9)
print(result)  

result = num.twoSum([3,2,4],6)
print(result) 

result = num.twoSum([3,3],6)
print(result)

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...