Thursday, March 14, 2013

Day 1 - leetcode 26, 27, remove

26 Remove Duplicates from Sorted Array
Solution #1
int removeDuplicates(int A[], int n) {
   // Start typing your C/C++ solution below
   // DO NOT write int main() function
   //int i = 0;
   int index=0,cur = 1;
   if (n==0) return 0;
   while (cur < n) {
           if (A[index] != A[cur]) {
                 index++;
              A[index] = A[cur];
           }
       cur++;
   }
   return index+1;
}
Solution #2
 int removeDuplicates(int A[], int n) {
       // Start typing your C/C++ solution below
       // DO NOT write int main() function
       if (n==0) return 0;
       int start=0;
       for (int i=0;i<n;i++) {
           if (A[start] != A[i]) {
               A[++start] = A[i];
               //start++;
           }
           
       }
       return start+1;
    }
27 Remove Element
Solution #1
int removeElement(int A[], int n, int elem) {
         // Start typing your C/C++ solution below
        // DO NOT write int main() function
         int start = 0;
         for(int i = 0; i < n; i++)
            if (elem != A[i])            {
                 A[start++] = A[i];            }
             
         return start;
   }

No comments:

Post a Comment