标签:
原题链接在这里:https://leetcode.com/problems/find-the-duplicate-number/
每次取 Math.abs(nums[i])为index, 然后跳到index上,如果这个数是正数,那么把它变成负数,如果是负数,说明之前已经有操作使其为负,就有重复,返回index.
AC Java:
1 public class Solution { 2 public int findDuplicate(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 for(int i = 0; i<nums.length; i++){ 7 int ind = Math.abs(nums[i]); 8 if(nums[ind] < 0){ 9 return ind; 10 } 11 nums[ind] = -nums[ind]; 12 } 13 return 0; 14 } 15 }
LeetCode Find the Duplicate Number
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4881212.html