c# solution is pretty slow - suggestions to improve efficiency?


  • 0
    T

    I'm getting ~360ms for the following code - any suggestions on how to make it better? (without drastically changing the solution) I'm curious on how to improve runtime speed.

    public class Solution {
        public int LongestConsecutive(int[] nums) {
            int max_length = 0;
            List<int> num_list = new List<int>(nums);
            while(num_list.Count > 0){
                int current = num_list[0];
                num_list.Remove(current);
                int length = 1;
                int one_bigger = current + 1;
                int one_smaller = current - 1;
                while(num_list.Contains(one_bigger)){
                    num_list.Remove(one_bigger);
                    one_bigger++;
                    length++;
                }            
                while(num_list.Contains(one_smaller)){
                    num_list.Remove(one_smaller);
                    one_smaller--;
                    length++;
                }
                if(length > max_length){
                    max_length=length;
                }
            }
            return max_length;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.