int NthUglyNumber(int n) { if(n == 1) return 1; List<long> arr = new List<long>(); // 这里用list,它会自己扩容,用数组就需要自己操作这些了 arr.Add(1); int[] uglyArr = {2,3,5}; HashSet<long> hs = new HashSet<long>(); hs.Add(1); HeapInsert(arr,0); long result = 0; for(int i=0;i<n;i++) { result = heapPop(arr); foreach(var y in uglyArr) { long temp = result*y; if(!hs.Contains(temp)) { hs.Add(temp); arr.Add(temp); HeapInsert(arr,arr.Count -1); } } } return (int)result; } long heapPop(List<long> arr) { swap(arr,arr.Count-1,0); var rt = arr[arr.Count-1]; arr.RemoveAt(arr.Count-1); // 这里传递0 ,heapSize是数量 HeapifyS(arr,arr.Count,0); return rt; } void HeapifyS(List<long> arr,int heapSize,int i) { var left = 2*i + 1; // 表示有孩子 while(left < heapSize) { var largest = left + 1 < heapSize && arr[left + 1] < arr[left] ? left + 1 : left; largest = arr[i] < arr[largest] ? i : largest; if(largest == i){ break; } swap(arr,i,largest); i = largest; left = i*2+1; } } // 构造小根堆 void HeapInsert(List<long> arr,int index) { while (index > (index - 1) / 2 && arr[index] < arr[(index - 1) / 2]) { swap(arr, index, (index - 1)/2); index = (index - 1) /2; } } void swap(List<long> arr,int i,int j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
标签:丑数,arr,index,int,List,算法,largest,小根堆,left From: https://www.cnblogs.com/Insist-Y/p/17320597.html