Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

java - Product of Array Except Self - Leet Code Time Limit Exceeded

I have been solving problem(Product of Array Except Self) on leetcode. My code compile successfully and passed 18 out of 19 test cases. I try to figure out the failed test case but no luck.

Exception: Time Limit Exceeded

Input: https://leetcode.com/submissions/detail/439297112/testcase/ - (70000 integers)

My Code

public int[] productExceptSelf(int[] nums) {
       int arr[] = { 1, 2, 3, 4 };
       return mySolution(arr);
   }
   
   public static int[] mySolution(int arr[]) {
       int size = arr.length;
       int j;
       int product;
       int[] result = new int[size];
       for (int i = 0; i < size; i++) {
           j = 0;
           product = 1;
           while (j < size) {
               if (j == i) {
                   j++;
                   continue;
               }
               product *= arr[j];
               j++;
           }

           result [i] = product;
       }

       return result;
   }



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this logic should reduce your time. I haven't checked it.

product = 1;
for (int i = 0; i < size; i++) {
    product *= arr[j];
}
for (int i = 0; i < size; i++) {
    result[i] = product/arr[i]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...