The spring constant, k, has units of N/m; mg = F which is N (N = kg*m/s2), and U = N/m * m = N as well since it is the specific force in this case. So setting F = U in this case should be acceptable since the units are the same and U is the specific force that is working on the object, yes?