Java val-to-index solution


  • 0
    D
    public class Solution {
        public List<Integer> findDisappearedNumbers(int[] nums) {
            List<Integer> disappear = new ArrayList<>();
            if (nums == null || nums.length <= 1) {
                return disappear;
            }
            for (int i = 0; i < nums.length; i++) {
                valToIndex(nums, i);
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == -1) {
                    disappear.add(i + 1);
                }
            }
            return disappear;
        }
    
        private void valToIndex(int[] nums, int index) {
            int thisjump = nums[index];
            nums[index] = -1;
            while (true) {
                int thatjump = nums[thisjump - 1];
                if (thatjump == -1) {
                    nums[thisjump - 1] = thisjump;
                    return;
                } else if (thatjump == thisjump) {
                    return;
                } else {
                    nums[thisjump - 1] = thisjump;
                    thisjump = thatjump;
                }
            }
        }
    }
    

Log in to reply
 

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