思路为力扣的某一道算法题 :283. 移动零 - 力扣(LeetCode) (leetcode-cn.com)
但是在处理集合元素为引用类型的数据时,需要注意数组是引用类型 ,数组元素改变的时候是引用地址(内存地址)的变化,
参考解释:C# 当数组参数引用传递 new 解惑 - 蜉蝣撼天 - 博客园 (cnblogs.com)
代码示例:
//测试类 public class ScoreRecord { public int Score { get; set; } public string Name { get; set; } }
public static ScoreRecord[] MoveZero(ScoreRecord[] nums) { int zeroNum = 0;//用来计算0的个数 for (int i = 0; i < nums.Length; i++) { if (nums[i].Score == 0) { zeroNum++; } else { //将nums[i] 跟前zersNum个交换 //并且将nums[i] 赋值为0 if (zeroNum != 0) { var _temp = nums[i]; ScoreRecord item = new ScoreRecord { Score = _temp.Score, Name = _temp.Name, }; var orgin = nums[i - zeroNum];//处理第一个元素为0的情况 nums[i - zeroNum] = item;//使用临时变量 避免引用同一个对象 nums[i].Score = 0; nums[i].Name = orgin.Name; } } } return nums; }
//前提,非0数据为有序数据 ScoreRecord[] scoreRecords = new ScoreRecord[] { new ScoreRecord{Score=0,Name="小李"}, new ScoreRecord{Score=12,Name="小白"}, new ScoreRecord{Score=56,Name="小黑"}, new ScoreRecord{Score=80,Name="小明"}, new ScoreRecord{Score=99,Name="小红"}, new ScoreRecord{Score=0,Name="小花"}, }; Console.WriteLine("原始:"); for (int i = 0; i < scoreRecords.Length; i++) { Console.WriteLine($"{scoreRecords[i].Score},{scoreRecords[i].Name}"); } Console.WriteLine(); Console.WriteLine(); var newArr = MoveZero(scoreRecords); Console.WriteLine("处理后:"); for (int i = 0; i < newArr.Length; i++) { Console.WriteLine($"{newArr[i].Score},{newArr[i].Name}"); } Console.ReadKey();
处理代码中,使用了额外的变量,避免引用了同一个对象
结果: