Swift二维数组:获取值为0且索引最小的元素求助
Hey Jonas, sorry your code isn't working out—let's get this sorted for you!
First off, let's make sure we're on the same page: you want to find the first occurrence of 0 in your 2D array (the one with the smallest indices, checking row by row left to right, then top to bottom). That makes sense!
Quick Example to Set the Scene
Say your 2D array looks like this:
my_2d_array = [ [1, 4, 7], [2, 0, 8], [3, 5, 0] ]
The first 0 here is at index (1, 1) (if we're using 0-based counting) — that's the one we want to grab.
Why Your Code Might Be Failing
Even though you didn't share your code, the most common issues here are:
- Not stopping the search as soon as you find the first 0 (so you end up grabbing a later one instead)
- Traversing the array in the wrong order (like column-first instead of row-first) which would skip the smallest-indexed 0
Working Solutions (Python Example)
Here are two straightforward ways to get what you need, depending on whether you want the element's indices or the element itself:
1. Get the Indices of the First 0
def find_first_zero_indices(arr): for row_num, row in enumerate(arr): for col_num, value in enumerate(row): if value == 0: return (row_num, col_num) # If no 0 exists in the array, return a default value (adjust as needed) return None # Test it out my_2d_array = [[1,4,7],[2,0,8],[3,5,0]] print(find_first_zero_indices(my_2d_array)) # Output: (1, 1)
2. Get the First 0 Element Directly
def get_first_zero_element(arr): for row in arr: for value in row: if value == 0: return value # No 0 found? Return a default return None print(get_first_zero_element(my_2d_array)) # Output: 0
How This Works
- We loop through the array row by row, left to right — this ensures we check elements in order of their index size
- As soon as we hit a 0, we immediately
returnit (or its indices) — this stops the search right away, so we don't waste time checking later elements - If there's no 0 in the array, we return
None— you can swap this out for something else (like-1) if that fits your use case better
If you're working with a different language (like JavaScript, Java, etc.), just let me know and I can tweak this solution to match!
内容的提问来源于stack exchange,提问作者user9469498

