C# O(n) Runtime O(1) space


  • 0
    K

    For each number i in the array, we mark index i - 1 with a negative sign, to indicate that we've seen it in the array. If we mark a number that already has a negative sign, then it's a duplicate.

    public class Solution {
        public IList<int> FindDuplicates(int[] nums) {
            IList<int> list = new List<int>();
            foreach(int i in nums){
                if(nums[Math.Abs(i) - 1] < 0) {
                    list.Add(Math.Abs(i));
                }
                else{
                    nums[Math.Abs(i) - 1] *= -1;
                }
            }
            
            return list;
        }
    }
    

Log in to reply
 

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